Search code examples
javascriptdatetimeculturejavascript-globalize

Globalize.js - how to parse date and time rather than just date


Globalize.js allows you to parse a date string based on the current culture applied

var date = Globalize.parseDate("17/07/2013"); //Wed Jul 17 00:00:00 PDT 2013

What I would like to do is parse a DateTime. The javascript Date object handles this, I'm surprised the Globalize.js library doesn't.

var date = new Date("07/17/2013 11:55 pm"); //Wed Jul 17 23:55:00 PDT 2013
var date = Globalize.parseDate("07/17/2013 11:55 pm"); //null

Am I missing something? I'm leaning towards parsing the time portion myself. Is there another library that extends Globalize.js that provides this kind of functionality? I've looked around but haven't found much.

UPDATE w/ accepted answer

You can parse the date if you know the format that the date is in.

    var date = Globalize.parseDate("17/07/2013 11:55 pm", "MM/dd/yyyy hh:mm tt"); 
    //date = null

In my example the date will be null because it expects the time period to be in the format of a.m or p.m.. Once I changed that I was able to parse a datetime.

   var date = Globalize.parseDate("17/07/2013 11:55 p.m.", "MM/dd/yyyy hh:mm tt"); 
   //date = Wed Jul 17 23:55:00 PDT 2013

Note: This is only applicable to the deprecated Globalize 0.x.

Note 2: Passing a hardcoded pattern is NOT an i18n recommendation.


Solution

  • If you know the pattern you are using:

    var date = Globalize.parseDate("07/17/2013 11:55 pm", "MM/dd/yyyy hh:mm tt");
    

    If you don't know the pattern:

    var date = Globalize.parseDate("07/17/2013 11:55 pm", Globalize.culture().calendar.patterns.d + " " + Globalize.culture().calendar.patterns.t)
    

    The line above is assuming current culture, if you need it for other culture or if you haven't established the local culture by calling Globalize.culture("") then just specify the culture on culture().

    I just ran on this scenario a few minutes ago, and found this solution, the latest it is messy, I hope there is a cleaner way to do this.

    Note: This is only applicable to the deprecated Globalize 0.x.

    Note 2: Passing a hardcoded pattern is NOT an i18n recommendation.