Parse 'Date & Time' string in Javascript which are of custom format
Asked Answered
W

6

22

I have to parse a date and time string of format "2015-01-16 22:15:00". I want to parse this into JavaScript Date Object. Any help on this?

I tried some jquery plugins, moment.js, date.js, xdate.js. Still no luck.

Weighty answered 17/1, 2015 at 17:38 Comment(2)
Please post your attempts. Otherwise it is hard to help.Sarong
possible duplicate of Where can I find documentation on formatting a date in JavaScriptAhem
C
47

With moment.js you can create a moment object using the String+Format constructor:

var momentDate = moment('2015-01-16 22:15:00', 'YYYY-MM-DD HH:mm:ss');

Then, you can convert it to JavaScript Date Object using toDate() method:

var jsDate = momentDate.toDate();
Cogent answered 17/1, 2015 at 17:46 Comment(2)
I tried using moment.js, but there was an error, "ReferenceError: moment is not defined". I had set the js path in my html too.Weighty
As Matt Johnson said, you have to follow the instructions for using moment.js in your browser application.Cogent
W
10

A better solution, I am now using date.js - https://code.google.com/p/datejs/

I included the script in my html page as this -

<script type="text/javascript" src="path/to/date.js"></script>

Then I simply parsed the date string "2015-01-16 22:15:00" with specifying the format as,

var dateString = "2015-01-16 22:15:00";
var date = Date.parse(dateString, "yyyy-MM-dd HH:mm:ss");
Weighty answered 18/1, 2015 at 5:34 Comment(1)
This fails for me. It seems that this date.js parse function only works on a single format. The second argument is ignored completely.Gladisgladney
C
8
new Date("2015-01-16T22:15:00")

See Date.parse().

The string must be in the ISO-8601 format. If you want to parse other formats use moment.js.

moment("2015-01-16 22:15:00").toDate();
Cancer answered 17/1, 2015 at 17:42 Comment(1)
This worked for me. What I did was a little hack improvement to the suggestion you provided, I have posted that solution in comment. Thanks :)Weighty
W
2

I was trying to use moment.js guys. But since I was having this error, "ReferenceError: moment is not defined", I had to skip it for now. I am using an temporary workaround for now.

function parseDate(dateString) {
    var dateTime = dateString.split(" ");
    var dateOnly = dateTime[0];
    var timeOnly = dateTime[1];

    var temp = dateOnly + "T" + timeOnly;
    return new Date(temp);
}
Weighty answered 17/1, 2015 at 18:11 Comment(0)
P
2

Bit annoying, but not hard to write a parsing method yourself without any dependencies. Regular expressions are great to check the input against one or many date formats. Though, the Date in the format provided 'just works' by now. I.e. new Date('2015-01-16 22:15:00') works for me in firefox. I did this for a date that looked like '08.10.2020 10:40:32', which does not work and maybe the date provided does not work in some browsers. But this way you can parse it without relying on built in parsing methods.

function getAsDate(input) {
    if (!input) return null;
    if (input instanceof Date) return input;

    // match '2015-01-16 22:15:00'
    const regexDateMatch = '^[0-9]{4}\-[0-9]{1,2}\-[0-9]{1,2}\ [0-9]{2}\:[0-9]{2}\:[0-9]{2}$';
    if(input.match(regexDateMatch)) {
        const [year, month, day, hours, minutes, seconds] = input.split(/[-: ]/).map(x => parseInt(x));
        const date = new Date(year, month, day, hours, minutes, seconds);
        return date;
    }

    // Date formats supported by JS
    return new Date(input);
}

Using Regex capture groups as suggested would also be an option.

function getAsDate(input) {
    if (!input) return null;
    if (input instanceof Date) return input;

    // match '2015-01-16 22:15:00'
    const regexDateMatch = '^([0-9]{4})\-([0-9]{1,2})\-([0-9]{1,2})\ ([0-9]{2})\:([0-9]{2})\:([0-9]{2})$';
    let match;
    if((match = input.match(regexDateMatch))) {
        const [year, month, day, hours, minutes, seconds] = match.slice(1, 7).map(x => parseInt(x));
        const date = new Date(year, month, day, hours, minutes, seconds);
        return date;
    }

    // Date formats supported by JS
    return new Date(input);
}

Hopefully JS upcomming temporal API will have a proper widely supported way to parse dates with a custom template. Then eventually we won´t have to deal with this anymore and all the other oddities of JS Date.

Paronomasia answered 6/12, 2021 at 13:1 Comment(1)
I like your answer (for flexible parsing and lack of dependencies) but would suggest it could be improved by using regex 'capture groups'. The regex would just need some parens adding to define the groups. Then year, month etc. could simply be accessed from the array returned from input.match()Polysyllable
E
1

If you are sure it's in the desired format and don't need to error check, you can parse it manually using split (and optionally replace). I needed to do something similar in my project (MM/DD/YYYY HH:mm:ss:sss) and modified my solution to fit your format. Notice the subtraction of 1 in the month.

var str = "2015-01-16 22:15:00"; 
//Replace dashes and spaces with : and then split on :
var strDate = str.replace(/-/g,":").replace(/ /g,":").split(":");
var aDate = new Date(strDate[0], strDate[1]-1, strDate[2], strDate[3], strDate[4], strDate[5]) ; 
Exquisite answered 19/7, 2017 at 22:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.