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.
I would look into moment.js, with it you can do
d = moment("17/07/2013 11:55 pm" , "DD/MM/YYYY HH:mm a"); // parsed as 11:55pm local time
d = d.toDate(); //get it as a native js date object
Unless you specify a timezone offset, parsing a string will create a date in the current users timezone.
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.
Globalize 1.x is based on CLDR and has a different API now. Follow the new code to accomplish what you need:
Globalize("en").parseDate("5/14/2015, 9:47 AM", {skeleton: "yMdhm"});
// > Thu May 14 2015 09:47:00 GMT-0300 (BRT)
More information and examples.
More information on how to load CLDR.
Notes on how to use CLDR patterns
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With