How can I convert string to datetime with format specification in JavaScript?

JavascriptDatetimeType Conversion

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

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

Solution 3 - Javascript

@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

Solution 4 - Javascript

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

Solution 5 - Javascript

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

Solution 6 - Javascript

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.

Solution 7 - Javascript

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

Solution 8 - Javascript

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

Solution 9 - Javascript

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]));
    }
}

Solution 10 - Javascript

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.

Solution 11 - Javascript

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.

Solution 12 - Javascript

Moment.js will handle this:

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

Solution 13 - Javascript

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.

Solution 14 - Javascript

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.

Solution 15 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSerhat OzgelView Question on Stackoverflow
Solution 1 - JavascriptChristophView Answer on Stackoverflow
Solution 2 - JavascriptRafael MuellerView Answer on Stackoverflow
Solution 3 - JavascriptOrganicPandaView Answer on Stackoverflow
Solution 4 - JavascriptTomalakView Answer on Stackoverflow
Solution 5 - JavascriptAaron GrayView Answer on Stackoverflow
Solution 6 - JavascriptAlexis AbrilView Answer on Stackoverflow
Solution 7 - JavascriptnavinView Answer on Stackoverflow
Solution 8 - Javascriptpuneet18View Answer on Stackoverflow
Solution 9 - JavascriptPavel V.View Answer on Stackoverflow
Solution 10 - JavascriptOliView Answer on Stackoverflow
Solution 11 - JavascriptAnton ValqkView Answer on Stackoverflow
Solution 12 - Javascriptsad comradeView Answer on Stackoverflow
Solution 13 - Javascriptamit pandyaView Answer on Stackoverflow
Solution 14 - JavascriptValentin RuskView Answer on Stackoverflow
Solution 15 - JavascriptAbhishek KanrarView Answer on Stackoverflow