Convert dd-mm-yyyy string to date
i am trying to convert a string in the format dd-mm-yyyy into a date object in JavaScript using the following:
var from = $("#datepicker").val(); var to = $("#datepickertwo").val(); var f = new Date(from); var t = new Date(to);
(«#datepicker»).val() contains a date in the format dd-mm-yyyy. When I do the following, I get «Invalid Date»:
15 Answers 15
Parse the string into the parts you need:
var from = $("#datepicker").val().split("-") var f = new Date(from[2], from[1] - 1, from[0])
var date = new Date("15-05-2018".replace( /(\d)-(\d)-(\d)/, "$2/$1/$3"))
Why not use regex?
Because you know you’ll be working on a string made up of three parts, separated by hyphens.
However, if you were looking for that same string within another string, regex would be the way to go.
Because you’re doing this more than once in your sample code, and maybe elsewhere in your code base, wrap it up in a function:
var from = $("#datepicker").val() var to = $("#datepickertwo").val() var f = toDate(from) var t = toDate(to)
Or if you don’t mind jQuery in your function:
var f = toDate("#datepicker") var t = toDate("#datepickertwo")
Modern JavaScript
If you’re able to use more modern JS, array destructuring is a nice touch also:
beat me to it. but I still use DateJs. This isn’t exactly correct due to a fence post error. the month is 0-11 so you need to subtract 1. f = new Date(from[2], from[1]-1, from[0]);
@AdrianLynch I’ve date in “Month dd, yyyy” formate only. Now, I’ve to convert it into “MM/dd/yyyy». Please suggest me.
regular expression example:
new Date( "13-01-2011".replace( /(\d)-(\d)-(\d)/, "$2/$1/$3") );
A revision that also takes / is delimiter and a year made of 2 digits (or any count bigger than 1): replace( /(\d<2>)[-/](\d<2>)[-/](\d+)/, «$2/$1/$3»)2>
Why should this be the selected answer @AdemirNuno? Why use RegEx for a string in a known format? You’re not looking for a pattern, you know the first number is the day, the second the month and the third the year. RegEx is the wrong tool for the job in this case.
A revision that takes non-digit delimiters, dates without leading zeroes and 2 or 4 digit years: new Date( «23. 2. 15».replace( /(\d+)[^d]+(\d+)[^d]+(\d+)/, «$2/$1/$3») ); en.wikipedia.org/wiki/Date_format_by_country
it’s so practice guy, thanks. my date format it comes with time, so i recode it as : ‘new Date( «13-01-2011».replace( /(\d<2>)-(\d<2>)-(\w)/, «$2/$1/$3») );’ is it right?2>
var from = "10-11-2011"; var numbers = from.match(/\d+/g); var date = new Date(numbers[2], numbers[0]-1, numbers[1]);
Match the digits and reorder them
Also the original question specified «dd-mm-yyyy», not «mm-dd-yyyy», so it’s still wrong (but only just).
var from = '11-04-2017' // OR $("#datepicker").val(); var milliseconds = moment(from, "DD-MM-YYYY").format('x'); var f = new Date(milliseconds)
Use this format: myDate = new Date(‘2011-01-03’); // Mon Jan 03 2011 00:00:00
@Diodeus even with the last edit this doesn’t quite work for me (with Chrome at least). It sets the date to ‘2011-01-03’ and the UTC time to 00:00:00 . So if the user’s time zone is less than UTC, it will actually be the day before.
var from = $("#datepicker").val(); var f = $.datepicker.parseDate("d-m-Y", from);
You should use $.datepicker.parseDate(«dd-mm-yy», from); to properly parse a date like 24-01-2017 , chek datepicker documentation at api.jqueryui.com/datepicker
The accepted answer kinda has a bug
var from = $("#datepicker").val().split("-") var f = new Date(from[2], from[1] - 1, from[0])
Consider if the datepicker contains «77-78-7980» which is obviously not a valid date. This would result in:
var f = new Date(7980, 77, 77); => Date 7986-08-15T22:00:00.000Z
Which is probably not the desired result.
The reason for this is explained on the MDN site:
Where Date is called as a constructor with more than one argument, if values are greater than their logical range (e.g. 13 is provided as the month value or 70 for the minute value), the adjacent value will be adjusted. E.g. new Date(2013, 13, 1) is equivalent to new Date(2014, 1, 1) .
A better way to solve the problem is:
const stringToDate = function(dateString) < const [dd, mm, yyyy] = dateString.split("-"); return new Date(`$-$-$`); >; console.log(stringToDate('04-04-2019')); // Date 2019-04-04T00:00:00.000Z console.log(stringToDate('77-78-7980')); // Invalid Date
This gives you the possibility to handle invalid input.
const date = stringToDate("77-78-7980"); if (date === "Invalid Date" || isNaN(date)) < console.log("It's all gone bad"); >else < // Do something with your valid date here >
How to convert dd/mm/yyyy string into JavaScript Date object? [duplicate]
ummm, unclear. By «normal date» what do you mean, a string? And by «javascript Date format» what do you mean, a string like you posted or an actual JavaScript Date object.
10 Answers 10
MM/DD/YYYY format
If you have the MM/DD/YYYY format which is default for JavaScript, you can simply pass your string to Date(string) constructor. It will parse it for you.
var dateString = "10/23/2015"; // Oct 23 var dateObject = new Date(dateString); document.body.innerHTML = dateObject.toString();
DD/MM/YYYY format — manually
If you work with this format, then you can split the date in order to get day, month and year separately and then use it in another constructor — Date(year, month, day) :
var dateString = "23/10/2015"; // Oct 23 var dateParts = dateString.split("/"); // month is 0-based, that's why we need dataParts[1] - 1 var dateObject = new Date(+dateParts[2], dateParts[1] - 1, +dateParts[0]); document.body.innerHTML = dateObject.toString();
For more information, you can read article about Date at Mozilla Developer Network.
DD/MM/YYYY — using moment.js library
Alternatively, you can use moment.js library, which is probably the most popular library to parse and operate with date and time in JavaScript:
var dateString = "23/10/2015"; // Oct 23 var dateMomentObject = moment(dateString, "DD/MM/YYYY"); // 1st argument - string, 2nd argument - format var dateObject = dateMomentObject.toDate(); // convert moment.js object to Date object document.body.innerHTML = dateObject.toString();
In all three examples dateObject variable contains an object of type Date , which represents a moment in time and can be further converted to any string format.
you should pass the correct type (number) to the constructor. var dateObject: Date = new Date(+dateParts[2], +dateParts[1] — 1, +dateParts[0]);
This one is giving Fri Oct 23 2015 00:00:00 GMT+0530 (IST), And if we need «23 Oct 2015» only not complete string
There’s only one country in the whole world using MM/DD/YYYY and what do they set as the default JavaScript format? So annoying.
you can change the date format from dd/mm/yyyy to mm/dd/yyyy and vice versa, using regex, with something like this: const originalDate = ’23/07/2020′; const newDate = originalDate.replace(/(1<2>)\/(8<2>)\/(5)/g,’$2/$1/$3′); // newDate = ’07/23/2020′;2>
You can no longer depend on JavaScript parsing MM/DD/YYYY natively, due to changes in the underlying ECMAScript spec. The formats a JavaScript engine will parse are implementation-dependent, with the only ones in the ECMAScript standard being the IETF standard and a form of ISO 8601 (see What string date format will javascript’s parse recognize?)
Here’s one I prepared earlier.
var dateString = "23/10/2015"; // Oct 23 var newData = dateString.replace(/(\d+[/])(\d+[/])/, '$2$1'); var data = new Date(newData); document.body.innerHTML = date.toString();ere
While most responses were tied to splitting strings or using native date methods, the two closely-related ones using RegEx (i.e., answer by [drgol] and comment by [Tomás Hugo Almeida]) are both instructive about the use of capturing groups. Their succinctness also helps illustrate the value of capturing and distinguishing that from matching — two related concepts that can confuse new RegEx users. This code block consolidates their 2 answers but see originals above: const origDate = ’23/07/2020′; const newDate = origDate.replace(/(\d+[/])(\d+[/])/, ‘$2$1′); // newDate = ’07/23/2020’;
I found the default JS date formatting didn’t work.
So I used toLocaleString with options
const event = new Date(); const options = < dateStyle: 'short' >; const date = event.toLocaleString('en', options);
Parsing a string to create another string that is then parsed by the built–in parser is not an efficient strategy, particularly when neither string is in a format supported by ECMA-262.
A more efficient strategy is to parse the string once and give the parts directly to the constructor, avoiding the second parse, e.g.
const parseDMY = s => < let [d, m, y] = s.split(/\D/); return new Date(y, m-1, d); >; console.log(parseDMY('23/10/2015').toString());
Date.parse only supports the formats produced by:
Parsing of any other format (including m/d/y) is implementation dependent.
Convert Date format from mm-dd-yyyy to yyyy-mm-dd in javascript
I am trying to convert Date format from mm-dd-yyyy to yyyy-mm-dd in javascript. I tried below code getting Invalid date.
var convertJSDate = function(dateTime) < var dateTime = dateTime.split(" "); var dateArr = dateTime[0].split("-"); //var timeArr = dateTime[2].split(":"); var date1= new Date(dateArr[2],dateArr[0],dateArr[1],0,0,0,0); return date1; >var startTime = convertJSDate("06-08-2015");
Here, I want to display the startTime as 2015-06-08 00:00:00 . Now I am getting return date1 as Invalid date . I don’t know where is the issue. Please help me.
3 Answers 3
I corrected your code, like that it should work:
var convertJSDate = function(dateTime) < var dateArr = dateTime.split("-"); var date1= new Date(dateArr[2] + "-" + dateArr[0] + "-" + dateArr[1]); return date1; >var startTime = convertJSDate("06-08-2015");
If you want to format the date in JavaScript, you may consider using moment.js.
Based on what I see from the documentation, the library may awesomely fit your need. With moment.js you can format Date like in C#:
moment().format('MMMM Do YYYY, h:mm:ss a'); // June 8th 2015, 8:15:34 pm moment().format('dddd'); // Monday moment().format("MMM Do YY"); // Jun 8th 15 moment().format('YYYY [escaped] YYYY');
Above are excerpt from moment.js documentation.