931

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.
Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
jslearner
  • 21,331
  • 18
  • 37
  • 35
  • 3
    possible duplicate of [convert Java datestring to javascript date](http://stackoverflow.com/questions/4679638/convert-java-datestring-to-javascript-date) and [a lot more](http://stackoverflow.com/search?q=javascript+date+parse+string) – Felix Kling Apr 11 '11 at 09:23
  • 3
    Oh I'm confused now. Do you want `Date -> String` or `String -> Date` ? – Felix Kling Apr 11 '11 at 09:57
  • 13
    consider http://momentjs.com/ – hanshenrik Mar 17 '15 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) – Dugini Vijay Jul 21 '20 at 22:46
  • What if `var st = "Monday, August 10th 2020"`? Any and for this? – LazyCoder Aug 14 '20 at 08:08
  • It's now 2021, consider to use `date-fns` lib, the method `parse` – Juan Salvador Jan 27 '21 at 21:23
  • I prefer `date-fns` over other libs, because it acts on the `Date` javascript` class, Specially when I fetch results from `PostgreSQL – Juan Salvador Jan 27 '21 at 22:10
  • `parse("Monday, August 10th 2020", "EEEE, mmmm do yyyy", new Date(),)` – Juan Salvador Jan 27 '21 at 22:50
  • If you have a [UNIX timestamp](//en.wikipedia.org/wiki/Unix_time) or a similar number like `1644861097000`, see [Convert a Unix timestamp to time in JavaScript](/q/847185/4642212). If you’re looking how to format a Date to a string, see [How to format a JavaScript date](/q/3552461/4642212). – Sebastian Simon Feb 14 '22 at 17:51
  • 1
    [Moment.js is now effectively deprecated](https://momentjs.com/docs/#/-project-status/) – Liam Apr 21 '22 at 10:24

35 Answers35

1063

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.

Community
  • 1
  • 1
Pavel Hodek
  • 14,319
  • 3
  • 32
  • 37
  • 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 '14 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. – Pavel Hodek Mar 15 '14 at 14:21
  • Unfortunately I bumped into the issue that ***it doesn't work for ALL users**. – Roman Podlinov Apr 03 '14 at 10:48
  • @Pavel Hodek Yes sure. I bumped into the same issue http://stackoverflow.com/questions/17959660/todatestring-decrements-my-date because it depends from time of the day & client location you may be in situation when the code works correctly for you, but incorrectly for other users. – Roman Podlinov Apr 04 '14 at 05:12
  • 5
    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 '14 at 08:41
  • new Date('1970-30-02') gives me invalid date in chrome – Ben Taliadoros Jul 21 '15 at 14:15
  • 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'). – Pavel Hodek Jul 22 '15 at 06:43
  • (+1) for Important note, I never faced this issue on my machine or my client's machine but when i deployed the code to client's server, it started misbehaving with all the dates. Strangely, if the month is December, it will show it as January next year. – Ali Baig Aug 27 '15 at 14:57
  • Hi, look at this: new Date('2011-04-11T00:00:00Z'); return Sun Apr 10 2011 21:00:00 GMT-0300 (ART) – Braian Mellor Jun 29 '16 at 14:48
  • I agree with RobG. Use the Date(year, month, day, hours, minutes, seconds, milliseconds) constructor to avoid any time zone ambiguity. All UTC/local conversions should be done on the server instead of trusting the browser. There are many cases when you'd generate HTML content on the server: for reports and just text - containing dates. You want to do the conversion in one place - knowing anything that goes to the browser, or is received from there is local. You'd need some initial handshake call to communicate the browser's time zone/offset to the server though. Not rocket science. – Alex Rogachevsky Aug 14 '16 at 19:39
  • I have this string `2016-10-29 18:03:23.626` how can i convert this string into JavaScript Date() object? – Arpit Kumar Oct 29 '16 at 13:24
  • @ArpitMeena Simply `moment('2016-10-29 18:03:23.626').toDate();`. See http://momentjs.com/docs/#/parsing/string/ – Pavel Hodek Oct 31 '16 at 09:38
  • doesnt work with dates DD/MM/YYYY and that's a format used in input fields... (in many places around the world) – razor Jan 12 '17 at 17:12
  • @razor: The Moment.js library works properly with date format you suggested, try: `moment("29/10/2016", "DD/MM/YYYYY").toDate()` – Pavel Hodek Jan 17 '17 at 21:11
  • Also worth referencing [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) – RobG Aug 07 '17 at 22:59
  • I have a date string that has already been converted to local time (I have no control over that) so it is in the format "2018-01-25T06:00:00". In Chrome and Edge new Date() converts properly to "Thu Jan 25 2018 06:00:00 GMT-0500 (Eastern Standard Time)" but in Safari it converts to "Thu Jan 25 2018 01:00:00 GMT-0500 (Eastern Standard Time)" because it is converting as UTC, not local. Is there a way to indicate it is local? – Christine Feb 07 '18 at 15:06
  • If you are stuck in Date Hell: const now = new Date(new Date().toLocaleString() + "Z"); – Radagast Oct 07 '19 at 17:51
  • @BenTaliadoros—ECMA-262 has required timestamps like '1970-02-30' to return an invalid Date since limited support for ISO 8601 formats was introduced (ECMAScript 2015?). It's in a format supported by the spec but isn't a valid date. – RobG Oct 11 '19 at 12:28
  • @Christine—not having a timezone or Z is supposed to mean local but Safari is buggy. The best advice is to avoid the built–in parser—use a library or bespoke parser. It's only a couple of lines of code to parse ISO 8601 timestamps, including validation of the format and values. – RobG Oct 11 '19 at 12:31
  • passing "yyyy-mm-dd" in the Date constructor is unreliable. b/c the Date constructor sets the day back by 1. This is a terrible inconsistency. "mm/dd/yyyy" converts fine. However, I need this to work as I've built a comparison prototype. However, in order to do this, I must first convert the ISO format to the conventional and how di I know if my comparison method is receiving ISO vs conventional. All that's left is to build a separate proto method who's job it is to convert all of the potential formats into one that Date can handle... in effect doing Date() job for it. – Clarence Jul 17 '21 at 22:16
  • The dash format might lead to unsuspected results ... https://stackoverflow.com/questions/70481329/creating-timezone-independent-dates-in-javascript – Ole Dec 25 '21 at 18:01
  • [Moment.js is now effectively deprecated](https://momentjs.com/docs/#/-project-status/) – Liam Apr 21 '22 at 10:24
429

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());
mic
  • 1,190
  • 1
  • 17
  • 29
Roman Podlinov
  • 23,806
  • 7
  • 41
  • 60
  • 73
    It's not crazy at all, the adjustment is most likely caused by [DST](http://en.wikipedia.org/wiki/Daylight_saving_time) kicking in. Dates in the format of `yyyy-MM-dd` are parsed as UTC and [toString](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toUTCString). – James Jun 11 '14 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]. – Adam Youngers Mar 02 '15 at 00:26
  • 4
    @AdamYoungers Due to Javascript counts months from 0: January - 0, February - 1, etc – Roman Podlinov Mar 02 '15 at 12:44
  • 1
    This answer suggests that the behavior in the example is incorrect. Per the spec: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date (see: datestring) the outputed value in the example would be correct – James Ross Nov 21 '17 at 21:15
  • I still get a wrong date for 22-12-2020 with bulletproof solution. This gave me `1928-06-10T16:00:00.000Z` – West Jan 06 '21 at 01:08
  • @West did you try '2020-12-22' instead of `22-12-2020` :) – Roman Podlinov Jan 11 '21 at 11:46
  • 21
    A nifty way to unpack arguments `var [YYYY, MM, DD] = '2014-04-03'.split('-')` – molexi Feb 09 '21 at 14:13
  • In my view, a better solution would be new Date('2014-04-03'+"T00:00:00"), because it will give you the same solution and it's simpler. Additionally this solution is more error proof, because doesn't accept month above 12 or day above 31, giving you an Invalid Date in that situation. – Claudio Augusto Pereira Rolim Mar 26 '21 at 21:59
164
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}
Roman Podlinov
  • 23,806
  • 7
  • 41
  • 60
94
function stringToDate(_date,_format,_delimiter)
{
            var formatLowerCase=_format.toLowerCase();
            var formatItems=formatLowerCase.split(_delimiter);
            var dateItems=_date.split(_delimiter);
            var monthIndex=formatItems.indexOf("mm");
            var dayIndex=formatItems.indexOf("dd");
            var yearIndex=formatItems.indexOf("yyyy");
            var month=parseInt(dateItems[monthIndex]);
            month-=1;
            var formatedDate = new Date(dateItems[yearIndex],month,dateItems[dayIndex]);
            return formatedDate;
}

stringToDate("17/9/2014","dd/MM/yyyy","/");
stringToDate("9/17/2014","mm/dd/yyyy","/")
stringToDate("9-17-2014","mm-dd-yyyy","-")
Kassem
  • 1,179
  • 8
  • 8
  • 3
    Handles dates from every variation not just US formatting – Mark Jones Oct 27 '15 at 11:45
  • 4
    @MarkJones Do not trust the `.indexOf()` method as it is not cross browser compatible without polyfils. Instead, use the more compatible `.match()` or `.test()` vanilla JS methods. – Alexander Dixon Jan 05 '17 at 14:55
  • 2
    Adding `var _delimiter = _format.match(/\W/g)[0];` at the beginning of the function you can get the delimiter automatically and prescind of the 3rd parameter. – campsjos Feb 23 '17 at 15:18
  • This date format is wrong. It's because `mm` is for minutes not months... use MM in your formats – vin shaba Sep 25 '21 at 18:18
50

Recommendation: I recommend to use a package for dates that contains a lot of formats because the timezone and format time management is really a big problem, moment js solve a lot of formats. You could parse easily date from a simple string to date but I think that is a hard work to support all formats and variations of dates.

Update: Moment is now deprecated, A good alternative for moment is datefns https://date-fns.org/


moment.js (http://momentjs.com/) is a complete and good package for use dates and supports ISO 8601 strings.

You could add a string date and format.

moment("12-25-1995", "MM-DD-YYYY");

And you could check if a date is valid.

moment("not a real date").isValid(); //Returns false

Some display examples

let dt = moment("02-01-2019", "MM-DD-YYYY");
console.log(dt.fromNow()+' |'+dt.format('LL')) 
// output: "3 months ago | February 1, 2019"

See documentation http://momentjs.com/docs/#/parsing/string-format/

Liam
  • 27,717
  • 28
  • 128
  • 190
Juan Caicedo
  • 1,425
  • 18
  • 31
  • 1
    Some [display examples](http://momentjs.com/docs/#/displaying/) `let dt = moment("02-01-2019", "MM-DD-YYYY");console.log(dt.fromNow()+' | '+dt.format('LL'))` outputs: "3 months ago | February 1, 2019" – CPHPython May 10 '19 at 13:28
  • Moment.js **is not deprecated**. From the link in the answer: "*We now generally consider Moment to be a legacy project in maintenance mode. It is not dead, but it is indeed done.*". – RobG Oct 29 '22 at 23:58
34

Pass it as an argument to Date():

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

You can access the date, month, year using, for example: dt.getMonth().

Karl Andrew
  • 1,563
  • 11
  • 14
  • 26
    i do `console.log(new Date('30-08-2018'))` and get invalid date – Dwigh Aug 30 '18 at 11:13
  • 10
    This answer ignores multiple complexities to this problem, for example, if I do this for a date `01/02/2020` on my computer (in the UK) it will return 1st Feburary where as if the same thing is done in the US it will return 2nd January. You should pretty much never use this naive implementation. Use [moment](https://stackoverflow.com/a/35847982/542251) instead. – Liam May 28 '20 at 08:02
30

If you can use the terrific luxon library you can easily parse your date using e.g.

var luxonDate = DateTime.fromISO("2014-09-15T09:00:00");

and can access the JS date object via

luxonDate().toJSDate();

The old answer used MomentJS

var momentDate = moment("2014-09-15 09:00:00");
momentDate ().toDate();
disco crazy
  • 31,313
  • 12
  • 80
  • 83
  • 5
    please note that moment works just fine without node – shaheer Feb 09 '15 at 05:08
  • I got NaN error in my android and IOS devices while using this code, however it was working in desktop. here is the code I was using before: var dateTimeOfTimeIn = new Date(year + "-" + month + "-" + day + "T" + data.timeIn); using this approach and moment library, my problem got solved and my code is now working fine in all of my devices! – Mehdi Jul 06 '18 at 04:49
  • [moment is now deprecated](https://momentjs.com/docs/#/-project-status/) – Liam Apr 21 '22 at 10:26
28

For those who are looking for a tiny and smart solution:

String.prototype.toDate = function(format)
{
  var normalized      = this.replace(/[^a-zA-Z0-9]/g, '-');
  var normalizedFormat= format.toLowerCase().replace(/[^a-zA-Z0-9]/g, '-');
  var formatItems     = normalizedFormat.split('-');
  var dateItems       = normalized.split('-');

  var monthIndex  = formatItems.indexOf("mm");
  var dayIndex    = formatItems.indexOf("dd");
  var yearIndex   = formatItems.indexOf("yyyy");
  var hourIndex     = formatItems.indexOf("hh");
  var minutesIndex  = formatItems.indexOf("ii");
  var secondsIndex  = formatItems.indexOf("ss");

  var today = new Date();

  var year  = yearIndex>-1  ? dateItems[yearIndex]    : today.getFullYear();
  var month = monthIndex>-1 ? dateItems[monthIndex]-1 : today.getMonth()-1;
  var day   = dayIndex>-1   ? dateItems[dayIndex]     : today.getDate();

  var hour    = hourIndex>-1      ? dateItems[hourIndex]    : today.getHours();
  var minute  = minutesIndex>-1   ? dateItems[minutesIndex] : today.getMinutes();
  var second  = secondsIndex>-1   ? dateItems[secondsIndex] : today.getSeconds();

  return new Date(year,month,day,hour,minute,second);
};

Example:

"22/03/2016 14:03:01".toDate("dd/mm/yyyy hh:ii:ss");
"2016-03-29 18:30:00".toDate("yyyy-mm-dd hh:ii:ss");
Arivan Bastos
  • 1,876
  • 1
  • 20
  • 28
  • 2
    Not a good idea to mess with the String.prototype, it can cause really hard to find bugs – Julian Knight Jul 09 '20 at 16:43
  • 2
    It is true that messing up with the String.prototype is not a good idea, but the ground base of this helps me a lot. I form it into a function to go save. – andre.hey Sep 28 '20 at 13:33
28

Just new Date(st);

Assuming that it's the proper format.

kirodge
  • 676
  • 5
  • 23
  • No, this is a terrible idea unless you are certain that the input is always going to be in a format that Date will parse correctly. It will break in various parts of the world. – Julian Knight Jul 09 '20 at 16:32
  • 1
    @JulianKnight - I *literally said* "Assuming that it's in the proper format". And no, it won't break in various parts of the world, lol –  Aug 17 '20 at 21:45
  • 6
    Then you didn't really answer the question. Please compare yours against the accepted answer. Your answer WILL break under many circumstances. How about `new Date("3/2/20")` - what does that produce for you? Do you think it produces the same answer for me? Unless we are in the same country, almost certainly not. As I said, it is a terrible idea. Sarcasm does not make it right. – Julian Knight Aug 20 '20 at 19:10
  • 1
    @JulianKnight -- ***IN THE PROPER FORMAT***. Your example has as much validity as `new Date('a tomato')`. ISO 8601 is a proper format. `3/2/20` is not. –  Dec 10 '21 at 16:44
  • Sorry but that is a very unhelpful reply. Of course ISO formats are the best approach in many cases but it isn't always feasible. What if this is about input from a website? Will you get everyone in the world and force them to use ISO date formats? The "PROPER" format depends on the context not some techie view of the world. – Julian Knight Dec 15 '21 at 17:40
20

new Date(2000, 10, 1) will give you "Wed Nov 01 2000 00:00:00 GMT+0100 (CET)"

See that 0 for month gives you January

Torsten Becker
  • 4,330
  • 2
  • 21
  • 22
17

That's the best and simpler solution in my view:

Just concatenate your date string (using ISO format) with "T00:00:00" in the end and use the JavaScript Date() constructor, like the example below.

const dateString = '2014-04-03'
var mydate = new Date(dateString + "T00:00:00");
console.log(mydate.toDateString());

And just a few details about the solution above (but optional reading):

In ISO format, if you provide time and Z is not present in the end of string, the date will be local time zone instead of UTC time zone. That means, when setting a date in this way, without specifying the time zone, JavaScript will use the local browser's time zone. And when getting a date, without specifying the time zone as well, the result is also converted to the browser's time zone. And, by default, almost every date method in JavaScript (except one) gives you a date/time in local time zone as well (you only get UTC if you specify UTC). So, using in local/browser time zone you probably won't get unwanted results because difference between your local/browse time zone and the UTC time zone, which is one of the main complaints with date string conversion. But if you will use this solution, understand your context and be aware of what you are doing. And also be careful that omitting T or Z in a date-time string can give different results in different browsers.

Important to note that the example above will give you exactly the same return to this example below, that is the second most voted answer in this question:

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());

The main difference is that the first example provided here is simpler and even more error proof than the second one (at least in my view, as explained below).

Because if you call the JavaScript Date() constructor date with just one date-string argument in ISO format (first example), it doesn't accept values above its logical limit (so, if you give 13 as month or 32 as day, you get Invalid Date).

But when you use the same constructor with multiple date-arguments (second example), parameters above it logical limit will be adjusted to the adjacent value and you won't get Invalid Date Error (so, if you give 13 as month, it will adjust to 1, instead of give you an Invalid Date).

Or an alternative (and third) solution would be mix both, use the first example just to validate the date-string and if it is valid use the second example (so you avoid possible browsers inconsistences of the first example and at the same time avoid the permission of parameters above it logical limit of the second example).

Like so (accepting partial dates as well):

function covertStringToDate(dateString) {
    //dateString should be in ISO format: "yyyy-mm-dd", "yyyy-mm" or "yyyy"
    if(new Date(dateString).toString() === "Invalid Date") {
        return false
    } else {
        const onlyNumbers = dateString.replace(/\D/g, ""); 
        const year = onlyNumbers.slice(0,4) 
        const month = onlyNumbers.slice(4,6)
        const day = onlyNumbers.slice(6,8)
        if(!month){
            return(new Date(year))
        } else if (!day) {
            return(new Date(year, month - 1))
        } else {
            return(new Date(year, month - 1, day))
        }        
    }
}

And a fourth alternative (and last suggestion) would be to use an appropriate third library (like moment or date-fns)

References:

15

If you want to convert from the format "dd/MM/yyyy". Here is an example:

var pattern = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/;
var arrayDate = stringDate.match(pattern);
var dt = new Date(arrayDate[3], arrayDate[2] - 1, arrayDate[1]);

This solution works in IE versions less than 9.

Alexandre N.
  • 2,594
  • 2
  • 28
  • 32
15

Timestamps should be casted to a Number

var ts = '1471793029764';
ts = Number(ts); // cast it to a Number
var date = new Date(ts); // works

var invalidDate = new Date('1471793029764'); // does not work. Invalid Date
Lucky Soni
  • 6,811
  • 3
  • 38
  • 57
  • 1
    What about the `undefined` value? Like: `var date = new Date(undefined)`? – Benny Code Nov 28 '16 at 14:13
  • 1
    @BennyNeugebauer well check if a value is undefined before you try to pass it to the Date constructor. Maybe you want to throw an exception or maybe you want to fallback to a default date, who knows? – Lucky Soni Dec 19 '16 at 17:34
11

Date.parse almost gets you what you want. It chokes on the am/pm part, but with some hacking you can get it to work:

var str = 'Sun Apr 25, 2010 3:30pm',
    timestamp;

timestamp = Date.parse(str.replace(/[ap]m$/i, ''));

if(str.match(/pm$/i) >= 0) {
    timestamp += 12 * 60 * 60 * 1000;
}
niksvp
  • 5,545
  • 2
  • 24
  • 41
10

Performance

Today (2020.05.08) I perform tests for chosen solutions - for two cases: input date is ISO8601 string (Ad,Bd,Cd,Dd,Ed) and input date is timestamp (At, Ct, Dt). Solutions Bd,Cd,Ct not return js Date object as results, but I add them because they can be useful but I not compare them with valid solutions. This results can be useful for massive date parsing.

Conclusions

  • Solution new Date (Ad) is 50-100x faster than moment.js (Dd) for all browsers for ISO date and timestamp
  • Solution new Date (Ad) is ~10x faster than parseDate (Ed)
  • Solution Date.parse(Bd) is fastest if wee need to get timestamp from ISO date on all browsers

enter image description here

Details

I perform test on MacOs High Sierra 10.13.6 on Chrome 81.0, Safari 13.1, Firefox 75.0. Solution parseDate (Ed) use new Date(0) and manually set UTC date components.

let ds = '2020-05-14T00:00Z'; // Valid ISO8601 UTC date
let ts = +'1589328000000';    // timestamp

let Ad = new Date(ds);
let Bd = Date.parse(ds);
let Cd = moment(ds);
let Dd = moment(ds).toDate();
let Ed = parseDate(ds);

let At = new Date(ts);
let Ct = moment(ts);
let Dt = moment(ts).toDate();

log = (n,d) => console.log(`${n}: ${+d} ${d}`);

console.log('from date string:', ds)
log('Ad', Ad);
log('Bd', Bd);
log('Cd', Cd);
log('Dd', Dd);
log('Ed', Ed);
console.log('from timestamp:', ts)
log('At', At);
log('Ct', Ct);
log('Dt', Dt);



function parseDate(dateStr) {
  let [year,month,day] = dateStr.split(' ')[0].split('-');
  let d=new Date(0);
  d.setUTCFullYear(year);
  d.setUTCMonth(month-1);
  d.setUTCDate(day)
  return d;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.1/moment-with-locales.min.js"></script>

This snippet only presents used soultions  

Results for chrome

enter image description here

Community
  • 1
  • 1
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
8

Convert to format pt-BR:

    var dateString = "13/10/2014";
    var dataSplit = dateString.split('/');
    var dateConverted;

    if (dataSplit[2].split(" ").length > 1) {

        var hora = dataSplit[2].split(" ")[1].split(':');
        dataSplit[2] = dataSplit[2].split(" ")[0];
        dateConverted = new Date(dataSplit[2], dataSplit[1]-1, dataSplit[0], hora[0], hora[1]);

    } else {
        dateConverted = new Date(dataSplit[2], dataSplit[1] - 1, dataSplit[0]);
    }

I hope help somebody!!!

6

I have created a fiddle for this, you can use toDate() function on any date string and provide the date format. This will return you a Date object. https://jsfiddle.net/Sushil231088/q56yd0rp/

"17/9/2014".toDate("dd/MM/yyyy", "/")
Sushil Mahajan
  • 137
  • 1
  • 6
  • 4
    Messing with String.prototype is likely to end in tears. – Julian Knight Jul 09 '20 at 16:37
  • This is a link to a solution, not a solution. To see the code for this solution, without having to go to a different site, [see this answer](https://stackoverflow.com/a/38593735/215552). – Heretic Monkey Sep 24 '20 at 20:14
5

For сonverting string to date in js i use http://momentjs.com/

moment().format('MMMM Do YYYY, h:mm:ss a'); // August 16th 2015, 4:17:24 pm
moment().format('dddd');                    // Sunday
moment().format("MMM Do YY");               // Aug 16th 15
moment().format('YYYY [escaped] YYYY');     // 2015 escaped 2015
moment("20111031", "YYYYMMDD").fromNow(); // 4 years ago
moment("20120620", "YYYYMMDD").fromNow(); // 3 years ago
moment().startOf('day').fromNow();        // 16 hours ago
moment().endOf('day').fromNow();          // in 8 hours
Alexey Popov
  • 76
  • 2
  • 8
  • 1
    moment() by default takes current date. How to format a string which is in "2016-06-27 17:49:51.951602+05:30" format using moment. – Zoran777 Jun 28 '16 at 08:17
5

I made this function to convert any Date object to a UTC Date object.

function dateToUTC(date) {
    return new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());
}


dateToUTC(new Date());
Andrew
  • 3,733
  • 1
  • 35
  • 36
4

You Can try this:

function formatDate(userDOB) {
  const dob = new Date(userDOB);

  const monthNames = [
    'January', 'February', 'March', 'April', 'May', 'June', 'July',
     'August', 'September', 'October', 'November', 'December'
  ];

  const day = dob.getDate();
  const monthIndex = dob.getMonth();
  const year = dob.getFullYear();

  // return day + ' ' + monthNames[monthIndex] + ' ' + year;
  return `${day} ${monthNames[monthIndex]} ${year}`;
}

console.log(formatDate('1982-08-10'));
Syed
  • 15,657
  • 13
  • 120
  • 154
4

This answer is based on Kassem's answer but it also handles two-digit years. I submitted an edit to Kassem's answer, but in case it wasn't approved, I'm also submitting this as a separate answer.

function stringToDate(_date,_format,_delimiter) {
        var formatLowerCase=_format.toLowerCase();
        var formatItems=formatLowerCase.split(_delimiter);
        var dateItems=_date.split(_delimiter);
        var monthIndex=formatItems.indexOf("mm");
        var dayIndex=formatItems.indexOf("dd");
        var yearIndex=formatItems.indexOf("yyyy");
        var year = parseInt(dateItems[yearIndex]); 
        // adjust for 2 digit year
        if (year < 100) { year += 2000; }
        var month=parseInt(dateItems[monthIndex]);
        month-=1;
        var formatedDate = new Date(year,month,dateItems[dayIndex]);
        return formatedDate;
}

stringToDate("17/9/14","dd/MM/yyyy","/");
stringToDate("17/9/2014","dd/MM/yyyy","/");
stringToDate("9/17/2014","mm/dd/yyyy","/")
stringToDate("9-17-2014","mm-dd-yyyy","-")
Daniel Patru
  • 1,968
  • 18
  • 15
3
var date = new Date(year, month, day);

or

var date = new Date('01/01/1970');

date string in format '01-01-1970' will not work in FireFox, So better use "/" instead of "-" in date format string.

Ravi
  • 59
  • 9
3

Yet another way to do it:

String.prototype.toDate = function(format) {
    format = format || "dmy";
    var separator = this.match(/[^0-9]/)[0];
    var components = this.split(separator);
    var day, month, year;
    for (var key in format) {
        var fmt_value = format[key];
        var value = components[key];
        switch (fmt_value) {
            case "d":
                day = parseInt(value);
                break;
            case "m":
                month = parseInt(value)-1;
                break;
            case "y":
                year = parseInt(value);
        }
    }
    return new Date(year, month, day);
};
a = "3/2/2017";
console.log(a.toDate("dmy"));
// Date 2017-02-03T00:00:00.000Z
Mackraken
  • 495
  • 4
  • 5
3

You can using regex to parse string to detail time then create date or any return format like :

//example : let dateString = "2018-08-17 01:02:03.4"

function strToDate(dateString){
    let reggie = /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2}).(\d{1})/
  , [,year, month, day, hours, minutes, seconds, miliseconds] = reggie.exec(dateString)
  , dateObject = new Date(year, month-1, day, hours, minutes, seconds, miliseconds);
  return dateObject;
}
alert(strToDate(dateString));
TungHarry
  • 1,097
  • 11
  • 26
2

If you need to check the contents of the string before converting to Date format:

// Convert 'M/D/YY' to Date()
mdyToDate = function(mdy) {
  var d = mdy.split(/[\/\-\.]/, 3);

  if (d.length != 3) return null;

  // Check if date is valid
  var mon = parseInt(d[0]), 
      day = parseInt(d[1]),
      year= parseInt(d[2]);
  if (d[2].length == 2) year += 2000;
  if (day <= 31 && mon <= 12 && year >= 2015)
    return new Date(year, mon - 1, day);

  return null; 
}
Adriano P
  • 2,045
  • 1
  • 22
  • 32
2

I have created parseDateTime function to convert the string to date object and it is working in all browser (including IE browser), check if anyone required, reference https://github.com/Umesh-Markande/Parse-String-to-Date-in-all-browser

    function parseDateTime(datetime) {
            var monthNames = [
                "January", "February", "March",
                "April", "May", "June", "July",
                "August", "September", "October",
                "November", "December"
              ];
            if(datetime.split(' ').length == 3){
                var date = datetime.split(' ')[0];
                var time = datetime.split(' ')[1].replace('.00','');
                var timearray = time.split(':');
                var hours = parseInt(time.split(':')[0]);
                var format = datetime.split(' ')[2];
                var bits = date.split(/\D/);
                date = new Date(bits[0], --bits[1], bits[2]); /* if you change format of datetime which is passed to this function, you need to change bits e.x ( bits[0], bits[1], bits[2 ]) position as per date, months and year it represent bits array.*/
                var day = date.getDate();
                var monthIndex = date.getMonth();
                var year = date.getFullYear();
                if ((format === 'PM' || format === 'pm') && hours !== 12) {
                    hours += 12;
                    try{  time = hours+':'+timearray[1]+':'+timearray[2] }catch(e){ time = hours+':'+timearray[1] }
                } 
                var formateddatetime = new Date(monthNames[monthIndex] + ' ' + day + '  ' + year + ' ' + time);
                return formateddatetime;
            }else if(datetime.split(' ').length == 2){
                var date = datetime.split(' ')[0];
                var time = datetime.split(' ')[1];
                var bits = date.split(/\D/);
                var datetimevalue = new Date(bits[0], --bits[1], bits[2]); /* if you change format of datetime which is passed to this function, you need to change bits e.x ( bits[0], bits[1], bits[2 ]) position as per date, months and year it represent bits array.*/
                var day = datetimevalue.getDate();
                var monthIndex = datetimevalue.getMonth();
                var year = datetimevalue.getFullYear();
                var formateddatetime = new Date(monthNames[monthIndex] + ' ' + day + '  ' + year + ' ' + time);
                return formateddatetime;
            }else if(datetime != ''){
                var bits = datetime.split(/\D/);
                var date = new Date(bits[0], --bits[1], bits[2]); /* if you change format of datetime which is passed to this function, you need to change bits e.x ( bits[0], bits[1], bits[2 ]) position as per date, months and year it represent bits array.*/
                return date;
            }
            return datetime;
        }

    var date1 = '2018-05-14 05:04:22 AM';   // yyyy-mm-dd hh:mm:ss A
    var date2 = '2018/05/14 05:04:22 AM';   // yyyy/mm/dd hh:mm:ss A
    var date3 = '2018/05/04';   // yyyy/mm/dd
    var date4 = '2018-05-04';   // yyyy-mm-dd
    var date5 = '2018-05-14 15:04:22';   // yyyy-mm-dd HH:mm:ss
    var date6 = '2018/05/14 14:04:22';   // yyyy/mm/dd HH:mm:ss

    console.log(parseDateTime(date1))
    console.log(parseDateTime(date2))
    console.log(parseDateTime(date3))
    console.log(parseDateTime(date4))
    console.log(parseDateTime(date5))
    console.log(parseDateTime(date6))

**Output---**
Mon May 14 2018 05:04:22 GMT+0530 (India Standard Time)
Mon May 14 2018 05:04:22 GMT+0530 (India Standard Time)
Fri May 04 2018 00:00:00 GMT+0530 (India Standard Time)
Fri May 04 2018 00:00:00 GMT+0530 (India Standard Time)
Mon May 14 2018 15:04:22 GMT+0530 (India Standard Time)
Mon May 14 2018 14:04:22 GMT+0530 (India Standard Time)
Umesh Markande
  • 289
  • 1
  • 6
1

ISO 8601-esque datestrings, as excellent as the standard is, are still not widely supported.

This is a great resource to figure out which datestring format you should use:

http://dygraphs.com/date-formats.html

Yes, that means that your datestring could be as simple as as opposed to

"2014/10/13 23:57:52" instead of "2014-10-13 23:57:52"

taveras
  • 485
  • 3
  • 12
0
                //little bit of code for Converting dates 

                var dat1 = document.getElementById('inputDate').value;
                var date1 = new Date(dat1)//converts string to date object
                alert(date1);
                var dat2 = document.getElementById('inputFinishDate').value;
                var date2 = new Date(dat2)
                alert(date2);
Pec1983
  • 346
  • 4
  • 8
0

var a = "13:15"
var b = toDate(a, "h:m")
//alert(b);
document.write(b);

function toDate(dStr, format) {
  var now = new Date();
  if (format == "h:m") {
    now.setHours(dStr.substr(0, dStr.indexOf(":")));
    now.setMinutes(dStr.substr(dStr.indexOf(":") + 1));
    now.setSeconds(0);
    return now;
  } else
    return "Invalid Format";
}
Kurenai Kunai
  • 1,842
  • 2
  • 12
  • 22
0

use this code : (my problem was solved with this code)

function dateDiff(date1, date2){
var diff = {}                           // Initialisation du retour
var tmp = date2 - date1;

tmp = Math.floor(tmp/1000);             // Nombre de secondes entre les 2 dates
diff.sec = tmp % 60;                    // Extraction du nombre de secondes

tmp = Math.floor((tmp-diff.sec)/60);    // Nombre de minutes (partie entière)
diff.min = tmp % 60;                    // Extraction du nombre de minutes

tmp = Math.floor((tmp-diff.min)/60);    // Nombre d'heures (entières)
diff.hour = tmp % 24;                   // Extraction du nombre d'heures

tmp = Math.floor((tmp-diff.hour)/24);   // Nombre de jours restants
diff.day = tmp;

return diff;

}

arogachev
  • 33,150
  • 7
  • 114
  • 117
Fetra
  • 9
  • 1
0

I wrote a reusable function that i use when i get date strings from the server.
you can pass your desired delimiter( / - etc..) that separates the day month and year in order to use the split() method.
you can see & test it on this working example.

<!DOCTYPE html>
<html>
  <head>
    <style>
    </style>
  </head>
  <body>
    <div>
      <span>day:
      </span> 
      <span id='day'>
      </span>
    </div>
    <div>
      <span>month:
      </span> 
      <span id='month'>
      </span>
    </div>
    <div>
      <span>year:
      </span> 
      <span id='year'>
      </span>
    </div>
    <br/>
    <input type="button" id="" value="convert" onClick="convert('/','28/10/1980')"/>
    <span>28/10/1980
    </span>
    <script>
      function convert(delimiter,dateString)
      {
        var splitted = dateString.split('/');
        // create a new date from the splitted string 
        var myDate = new Date(splitted[2],splitted[1],splitted[0]);
        // now you can access the Date and use its methods 
        document.getElementById('day').innerHTML = myDate.getDate();
        document.getElementById('month').innerHTML = myDate.getMonth();
        document.getElementById('year').innerHTML = myDate.getFullYear();
      }
    </script>
  </body>
</html>
Jonathan Applebaum
  • 5,738
  • 4
  • 33
  • 52
0

Yet another way to do it is to build a regex with named capture groups over the format string and then use that regex to extract the day, month and year from the date string:

function parseDate(dateStr, format) {
  const regex = format.toLocaleLowerCase()
    .replace(/\bd+\b/, '(?<day>\\d+)')
    .replace(/\bm+\b/, '(?<month>\\d+)')
    .replace(/\by+\b/, '(?<year>\\d+)')
  
  const parts = new RegExp(regex).exec(dateStr) || {};
  const { year, month, day } = parts.groups || {};
  return parts.length === 4 ? new Date(year, month-1, day) : undefined;
}

const printDate = x => console.log(x ? x.toLocaleDateString() : x);

printDate(parseDate('05/11/1896', 'dd/mm/YYYY'));
printDate(parseDate('07-12-2000', 'dd-mm-yy'));
printDate(parseDate('07:12:2000', 'dd:mm:yy'));
printDate(parseDate('2017/6/3', 'yy/MM/dd'));
printDate(parseDate('2017-6-15', 'y-m-d'));
printDate(parseDate('2015 6 25', 'y m d'));
printDate(parseDate('2015625', 'y m d')); // bad format
jo_va
  • 13,504
  • 3
  • 23
  • 47
  • nice solution, but you maybe are not aware that Firefox still does not support RegExp named groups - https://bugzilla.mozilla.org/show_bug.cgi?id=1362154 (PS: it's not me who downvoted your answer) – qdev Aug 22 '19 at 19:59
0

As an addon to what has been explained here, you can create your Date with new Date() and format it with the incredibly useful toLocaleDateString() function

An example:

console.log(new Date('1970-01-01').toLocaleDateString('es-ES')) // --> This will output '1/1/1970'

S. Dre
  • 647
  • 1
  • 4
  • 18
-3

You can also do: mydate.toLocaleDateString();

-10

use this format....

//get current date in javascript

  var currentDate = new Date();


// for getting a date from a textbox as string format

   var newDate=document.getElementById("<%=textBox1.ClientID%>").value;

// convert this date to date time

   var MyDate = new Date(newDate);
GetBackerZ
  • 448
  • 5
  • 12