228

How can I convert a string to a date time object in javascript by specifying a format string?

I am looking for something like:

var dateTime = convertToDateTime("23.11.2009 12:34:56", "dd.MM.yyyy HH:mm:ss");
Serhat Ozgel
  • 23,496
  • 29
  • 102
  • 138
  • 2
    BTW dots and hyphens can fail as date separators, slashes are okay, so (to the limits of my tests) Javascript will accept "2011/08/22 10:30:00" but not yet (despite ISO 8601) "2011-09-02 15:58:40" which - it is claimed - is supported in Javascript 1.8.5 on. – Dave Everitt Sep 02 '11 at 15:45
  • Date.parse function parse the date string which is in "mm/dd/yyyy" format. Please convert the string to "mm/dd/yyyy" format before applying Parse. –  Sep 22 '11 at 10:30
  • Why not supply the date in the format required? I do it like new Date('2012 11 25 18:00:00'); and it works! – foxybagga Dec 25 '12 at 12:55

15 Answers15

110

Use new Date(dateString) if your string is compatible with Date.parse(). If your format is incompatible (I think it is), you have to parse the string yourself (should be easy with regular expressions) and create a new Date object with explicit values for year, month, date, hour, minute and second.

Ry-
  • 218,210
  • 55
  • 464
  • 476
Christoph
  • 164,997
  • 36
  • 182
  • 240
  • 2
    Date.parse is the best solution! It parse almost everything! +1 – ianaz Aug 30 '12 at 07:51
  • 13
    @ianaz: ALMOST everything used in America, but missing the format used by large portion of Europe is too big "almost". But new Date is a good basis for custom functions. – Pavel V. Feb 05 '16 at 10:27
  • new Date(dateString) worked fine for me, Date.parse() instead converts to milliseconds and so returns a number not a Date type. – Reagan Ochora May 27 '17 at 00:35
86

I think this can help you: http://www.mattkruse.com/javascript/date/

There's a getDateFromFormat() function that you can tweak a little to solve your problem.

Update: there's an updated version of the samples available at javascripttoolbox.com

Samuel Liew
  • 76,741
  • 107
  • 159
  • 260
Rafael Mueller
  • 6,028
  • 3
  • 24
  • 28
73

@Christoph Mentions using a regex to tackle the problem. Here's what I'm using:

var dateString = "2010-08-09 01:02:03";
var reggie = /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/;
var dateArray = reggie.exec(dateString); 
var dateObject = new Date(
    (+dateArray[1]),
    (+dateArray[2])-1, // Careful, month starts at 0!
    (+dateArray[3]),
    (+dateArray[4]),
    (+dateArray[5]),
    (+dateArray[6])
);

It's by no means intelligent, just configure the regex and new Date(blah) to suit your needs.

Edit: Maybe a bit more understandable in ES6 using destructuring:

let dateString = "2010-08-09 01:02:03"
  , reggie = /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/
  , [, year, month, day, hours, minutes, seconds] = reggie.exec(dateString)
  , dateObject = new Date(year, month-1, day, hours, minutes, seconds);

But in all honesty these days I reach for something like Moment

OrganicPanda
  • 2,667
  • 1
  • 27
  • 28
  • 19
    @bažmegakapa instead of crying you could perhaps have edited the answer and added the 'var's yourself? – OrganicPanda Aug 31 '12 at 20:34
  • Why are you using the `/g` flag, only to set `lastIndex` to `0` afterwards? Just don't use a global match. – Ry- Sep 01 '12 at 01:56
  • 1
    @minitech The `/g` was a sloppy copy/paste from an existing project. `lastindex` was added by an editor (to combat the `\g` I suppose?). I'll remove them now. Thank you for pointing that out. – OrganicPanda Sep 03 '12 at 10:54
  • 1
    very nice anwer ..really useful to me – Jethik Aug 12 '13 at 13:38
  • Any comments about how one can add timezone into this too? – Sagar Ranglani Nov 26 '21 at 07:58
  • @SagarRanglani honestly it's best to use a library for this these days, this answer was ok in 2011 but now I would use date-fns https://date-fns.org or similar – OrganicPanda Nov 26 '21 at 13:08
  • I was working in a restricted env so to speak, so wanted to do it nativly. I ended up creating an ISO string with these vars along with timezone to initialize the date. That worked! – Sagar Ranglani Nov 26 '21 at 19:21
15

No sophisticated date/time formatting routines exist in JavaScript.

You will have to use an external library for formatted date output, "JavaScript Date Format" from Flagrant Badassery looks very promising.

For the input conversion, several suggestions have been made already. :)

Tomalak
  • 332,285
  • 67
  • 532
  • 628
13

Check out Moment.js. It is a modern and powerful library that makes up for JavaScript's woeful Date functions (or lack thereof).

Aaron Gray
  • 11,283
  • 7
  • 55
  • 61
  • 5
    I didn't downvote, but perhaps it would have been nice to know exactly which function in Moment.js would give the desired behaviour (for us lazy people who are already using Moment.js but don't know the particular function to use). – Matt Oct 29 '15 at 21:45
  • The localization looks promising, pick any central-european locale for the dot format. However, I didn't test it and the full datetime format is not in the examples I've seen. – Pavel V. Feb 05 '16 at 10:16
  • 1
    I didn't downvote, but I just wanted to tell that this is slow. For desktop ok, but for mobile might be too slow (depending your needs). – gabn88 May 09 '16 at 09:00
12

Just for an updated answer here, there's a good js lib at http://www.datejs.com/

Datejs is an open source JavaScript Date library for parsing, formatting and processing.

Pavel Kovalev
  • 7,521
  • 5
  • 45
  • 67
Alexis Abril
  • 6,389
  • 6
  • 33
  • 53
  • Rolled back that edit, although very helpful it should be added as a comment or separate answer. – Alexis Abril Aug 31 '12 at 19:33
  • It was too long for a comment anyway, and adding a duplicated answer is wrong. This question has over 155,000 views - let's give these people as much information as possible! (by the way - it is very common in Stack Overflow to edit an existing answer - you would probably feel worse if I just copied your answer...) – Kobi Sep 02 '12 at 04:58
  • 1
    And anyway, if you don't like my edit that is fine, but please expand your answer - "Just for an updated answer here" is a filler, and it is missing some details. This question is getting [some attention](http://meta.stackexchange.com/questions/145301/what-can-be-done-with-a-blatantly-wrong-answer-to-a-popular-question) at the moment, by the way, which is the reason you suddenly got 5 votes. – Kobi Sep 02 '12 at 05:02
7
var temp1 = "";
var temp2 = "";

var str1 = fd; 
var str2 = td;

var dt1  = str1.substring(0,2);
var dt2  = str2.substring(0,2);

var mon1 = str1.substring(3,5);
var mon2 = str2.substring(3,5);

var yr1  = str1.substring(6,10);  
var yr2  = str2.substring(6,10); 

temp1 = mon1 + "/" + dt1 + "/" + yr1;
temp2 = mon2 + "/" + dt2 + "/" + yr2;

var cfd = Date.parse(temp1);
var ctd = Date.parse(temp2);

var date1 = new Date(cfd); 
var date2 = new Date(ctd);

if(date1 > date2) { 
    alert("FROM DATE SHOULD BE MORE THAN TO DATE");
}
navin
  • 87
  • 1
  • 1
7
time = "2017-01-18T17:02:09.000+05:30"

t = new Date(time)

hr = ("0" + t.getHours()).slice(-2);
min = ("0" + t.getMinutes()).slice(-2);
sec = ("0" + t.getSeconds()).slice(-2);

t.getFullYear()+"-"+t.getMonth()+1+"-"+t.getDate()+" "+hr+":"+min+":"+sec
puneet18
  • 4,341
  • 2
  • 21
  • 27
6

External library is an overkill for parsing one or two dates, so I made my own function using Oli's and Christoph's solutions. Here in central Europe we rarely use aything but the OP's format, so this should be enough for simple apps used here.

function ParseDate(dateString) {
    //dd.mm.yyyy, or dd.mm.yy
    var dateArr = dateString.split(".");
    if (dateArr.length == 1) {
        return null;    //wrong format
    }
    //parse time after the year - separated by space
    var spacePos = dateArr[2].indexOf(" ");
    if(spacePos > 1) {
        var timeString = dateArr[2].substr(spacePos + 1);
        var timeArr = timeString.split(":");
        dateArr[2] = dateArr[2].substr(0, spacePos);
        if (timeArr.length == 2) {
            //minutes only
            return new Date(parseInt(dateArr[2]), parseInt(dateArr[1]-1), parseInt(dateArr[0]), parseInt(timeArr[0]), parseInt(timeArr[1]));
        } else {
            //including seconds
            return new Date(parseInt(dateArr[2]), parseInt(dateArr[1]-1), parseInt(dateArr[0]), parseInt(timeArr[0]), parseInt(timeArr[1]), parseInt(timeArr[2]))
        }
    } else {
        //gotcha at months - January is at 0, not 1 as one would expect
        return new Date(parseInt(dateArr[2]), parseInt(dateArr[1] - 1), parseInt(dateArr[0]));
    }
}
Community
  • 1
  • 1
Pavel V.
  • 2,653
  • 10
  • 43
  • 74
4

Date.parse() is fairly intelligent but I can't guarantee that format will parse correctly.

If it doesn't, you'd have to find something to bridge the two. Your example is pretty simple (being purely numbers) so a touch of REGEX (or even string.split() -- might be faster) paired with some parseInt() will allow you to quickly make a date.

Oli
  • 235,628
  • 64
  • 220
  • 299
3

Just to give my 5 cents.

My date format is dd.mm.yyyy (UK format) and none of the above examples were working for me. All the parsers were considering mm as day and dd as month.

I've found this library: http://joey.mazzarelli.com/2008/11/25/easy-date-parsing-with-javascript/ and it worked, because you can say the order of the fields like this:

>>console.log(new Date(Date.fromString('09.05.2012', {order: 'DMY'})));
Wed May 09 2012 00:00:00 GMT+0300 (EEST)

I hope that helps someone.

Anton Valqk
  • 747
  • 6
  • 11
1

Moment.js will handle this:

var momentDate = moment('23.11.2009 12:34:56', 'DD.MM.YYYY HH:mm:ss');
var date = momentDate.;
sad comrade
  • 1,341
  • 19
  • 21
  • 1
    While moment.js is great, there are a plethora of use cases where you have to just use native Javascript. My current use-case is a Map function in CouchDB – Zach Smith Jun 27 '16 at 07:29
1

You can use the moment.js library for this. I am using only to get time-specific output but you can select what kind of format you want to select.

Reference:

1. moment library: https://momentjs.com/

2. time and date specific functions: https://timestamp.online/article/how-to-convert-timestamp-to-datetime-in-javascript

convertDate(date) {
        var momentDate = moment(date).format('hh : mm A');
        return momentDate;
}

and you can call this method like:

this.convertDate('2020-05-01T10:31:18.837Z');

I hope it helps. Enjoy coding.

amit pandya
  • 1,384
  • 13
  • 22
0
//Here pdate is the string date time
var date1=GetDate(pdate);
    function GetDate(a){
        var dateString = a.substr(6);
        var currentTime = new Date(parseInt(dateString ));
        var month =("0"+ (currentTime.getMonth() + 1)).slice(-2);
        var day =("0"+ currentTime.getDate()).slice(-2);
        var year = currentTime.getFullYear();
        var date = day + "/" + month + "/" + year;
        return date;
    }
Abhishek Kanrar
  • 418
  • 4
  • 6
0

To fully satisfy the Date.parse convert string to format dd-mm-YYYY as specified in RFC822, if you use yyyy-mm-dd parse may do a mistakes.

Valentin Rusk
  • 630
  • 5
  • 13
  • FYI, From RFC 822(page: 25. Partially cleaned to meet text length for comment): August 13, 1982 - 25 - RFC #822 5. DATE AND TIME SPECIFICATION 5.1. SYNTAX date-time = [ day "," ] date time ; dd mm yy hh:mm:ss zzz day = "Mon" / "Tue" / "Wed" / "Thu" / "Fri" / "Sat" / "Sun" date = 1*2DIGIT month 2DIGIT ; day month year e.g. 20 Jun 82 month = "Jan" / "Feb" / "Mar" / "Apr" / "May" / "Jun" / "Jul" / "Aug" / "Sep" / "Oct" / "Nov" / "Dec" – Valentin Rusk Jan 12 '14 at 16:20