232

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");
3
  • 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. Commented Sep 2, 2011 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. Commented Sep 22, 2011 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! Commented Dec 25, 2012 at 12:55

14 Answers 14

111

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Date.parse is the best solution! It parse almost everything! +1
@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.
new Date(dateString) worked fine for me, Date.parse() instead converts to milliseconds and so returns a number not a Date type.
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

5 Comments

TypeError: Object Date has no method 'getDateFromFormat'
+1, good library..pure javascript...it's fantastic. thank you
Both links are dead
If you can, please update the link. This doesn't help anymore.
Unfortunately, the javascripttoolbox.com link is also down.
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

7 Comments

@bažmegakapa instead of crying you could perhaps have edited the answer and added the 'var's yourself?
Why are you using the /g flag, only to set lastIndex to 0 afterwards? Just don't use a global match.
@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.
very nice anwer ..really useful to me
Any comments about how one can add timezone into this too?
|
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. :)

1 Comment

"have to" is relative. Of course you can build your own implementation. :)
13

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

3 Comments

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).
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.
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).
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");
}

Comments

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

2 Comments

plus 1 after calling the function getmonth() seems wrong
t.getMonth()+1 is correct as Date.getMonth() returns 0 based value.
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]));
    }
}

Comments

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.

Comments

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.

2 Comments

Links now dead!
Well... a quick archive.org showed: bitbucket.org/mazzarelli/js-date/downloads is the project url.
1

Moment.js will handle this:

var momentDate = moment('23.11.2009 12:34:56', 'DD.MM.YYYY HH:mm:ss');
var date = momentDate.;

1 Comment

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
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.

Comments

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.

1 Comment

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"
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;
    }

2 Comments

The querist asked for specifying a format string.
@Armali Input parameter like "/Date(1552415400000)/" in string format

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.