I have a timestamp that looks like this: "2012-12-29T20:00:00Z". What is the best way to convert that to month and date? Something like Dec 29.
3 Answers
I don't think there is a simple way to do so. but there are some libraries for this purpose. Like this one
And if you don't care about localization problem, just use internal Date object's prototype.
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date
7 Comments
new Date('2012-12-29T20:00:00Z') will parse it.Use the built-in Date object.
// Date.parse parses an ISO date
var d = new Date( Date.parse( '2012-12-29T20:00:00Z' ) );
console.log( d.toString() ); // "Sat Dec 29 2012 21:00:00 GMT+0100 (Paris, Madrid)"
console.log( d.toString().substr( 4, 6 ) ); // "Dec 29"
Note that substr will always work since days always have 3 characters, months always have 3 and dates always have 2.
If you don't want to use substr, there is no way to get "Dec" straight out. You can play with a mapping array however, like the following:
console.log( d.getMonth() ); // 11
var mapping = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ];
console.log( mapping[ d.getMonth() ] + ' ' + d.getDate() ); // "Dec 29"
This takes advantage of the fact that an array's index starts at 0, just like d.getMonth().
For IE8 support of Date.parse, I suggest you use the following shim (from ES5-shim): https://gist.github.com/303249
6 Comments
Date.parse and a shim that will make it work everywhere :-)You can convert the string to a Date Object using new Date("2012-12-29T20:00:00Z") which in my timezone results in Sat Dec 29 2012 21:00:00 GMT+0100 (W. Europe Standard Time). There are some datatime frameworks to pick from for formatting that, like datejs. I've cooked up a simple one in this jsfiddle, may be a starting point for you. I've added your ISO-date to the examples. It also works for older browsers.
2 Comments
Dec 29 from a date string. I was just pointing out the possibilities