Categories
date date-parsing javascript

Parsing a string to a date in JavaScript

865

How can I convert a string to a Date object in JavaScript?

var st = "date in some format"
var dt = new Date();

var dt_st = // st in Date format, same as dt.

10

  • 3

    possible duplicate of convert Java datestring to javascript date and a lot more

    Apr 11, 2011 at 9:23


  • 3

    Oh I’m confused now. Do you want Date -> String or String -> Date ?

    Apr 11, 2011 at 9:57

  • 13

    consider momentjs.com

    Mar 17, 2015 at 11:23

  • Simple solution: Use ISOString formatting var st = “05/05/2020” var dateTime1 = new Date(st).toISOString().replace(/T.+/, ‘ 00:00:00’) console.log(dateTime1)

    Jul 21, 2020 at 22:46

  • What if var st = "Monday, August 10th 2020"? Any and for this?

    – LazyCoder

    Aug 14, 2020 at 8:08

1003

The best string format for string parsing is the date ISO format together with the JavaScript Date object constructor.

Examples of ISO format: YYYY-MM-DD or YYYY-MM-DDTHH:MM:SS.

But wait! Just using the “ISO format” doesn’t work reliably by itself. String are sometimes parsed as UTC and sometimes as localtime (based on browser vendor and version). The best practice should always be to store dates as UTC and make computations as UTC.

To parse a date as UTC, append a Z – e.g.: new Date('2011-04-11T10:20:30Z').

To display a date in UTC, use .toUTCString(),
to display a date in user’s local time, use .toString().

More info on MDN | Date and this answer.

For old Internet Explorer compatibility (IE versions less than 9 do not support ISO format in Date constructor), you should split datetime string representation to it’s parts and then you can use constructor using datetime parts, e.g.: new Date('2011', '04' - 1, '11', '11', '51', '00'). Note that the number of the month must be 1 less.


Alternate method – use an appropriate library:

You can also take advantage of the library Moment.js that allows parsing date with the specified time zone.

22

  • I also had to use the “split the string” method for safari for the same “Nan” issue Paul Tomblin brought up. new Date(‘2011-04-11 11:51:00’) would return ‘invalid date’.

    – Amos

    Mar 14, 2014 at 21:47

  • 2

    @Amos: Notice the letter T, which separates the date and time. If you write new Date('2011-04-11T11:51:00') the date created is valid.

    Mar 15, 2014 at 14:21


  • Unfortunately I bumped into the issue that *it doesn’t work for ALL users.

    Apr 3, 2014 at 10:48

  • 4

    Letting Date parse a string is the worst way to create a Date object. Far better to parse the string manually and call Date as a constructor. Some browsers will treat an ISO string without timezone as UTC, others as local.

    – RobG

    Apr 26, 2014 at 8:41


  • 8

    @Ben Taliadoros: Yes, it is invalid in all common browsers, new Date('1970-30-02') is invalid date because there is not 30 months in a year. You can’t overflow months but when you overflow days then it resolves in Chrome and Firefox to a valid date: new Date('1970-02-30') is then the same day as new Date(‘1970-03-02’).

    Jul 22, 2015 at 6:43

391

Unfortunately I found out that

var mydate = new Date('2014-04-03');
console.log(mydate.toDateString());

returns “Wed Apr 02 2014”. I know it sounds crazy, but it happens for some users.

The bulletproof solution is the following:

var parts="2014-04-03".split('-');
// Please pay attention to the month (parts[1]); JavaScript counts months from 0:
// January - 0, February - 1, etc.
var mydate = new Date(parts[0], parts[1] - 1, parts[2]); 
console.log(mydate.toDateString());

9

  • 68

    It’s not crazy at all, the adjustment is most likely caused by DST kicking in. Dates in the format of yyyy-MM-dd are parsed as UTC and toString returns the local time therefore depending on the users timezone it can most definitely return different results. If always want the time as UTC then you should use toUTCString.

    – James

    Jun 11, 2014 at 12:29


  • Been banging my head on this one. This seems to work, but I don’t understand why you used parts[0]-1 and not just parts[0].

    Mar 2, 2015 at 0:26

  • 4

    @AdamYoungers Due to Javascript counts months from 0: January – 0, February – 1, etc

    Mar 2, 2015 at 12:44

  • 1

    This answer suggests that the behavior in the example is incorrect. Per the spec: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… (see: datestring) the outputed value in the example would be correct

    Nov 21, 2017 at 21:15

  • 11

    A nifty way to unpack arguments var [YYYY, MM, DD] = '2014-04-03'.split('-')

    – Smartens

    Feb 9, 2021 at 14:13


154

var st = "26.04.2013";
var pattern = /(\d{2})\.(\d{2})\.(\d{4})/;
var dt = new Date(st.replace(pattern,'$3-$2-$1'));

And the output will be:

dt => Date {Fri Apr 26 2013}

3