user1082754
user1082754

Reputation:

Convert timestamp with JavaScript

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.

Upvotes: 0

Views: 512

Answers (3)

KooiInc
KooiInc

Reputation: 123016

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.

Upvotes: 0

Florian Margaine
Florian Margaine

Reputation: 60835

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

Upvotes: 0

xiaoyi
xiaoyi

Reputation: 6751

I don't think there is a simple way to do so. but there are some libraries for this purpose. Like this one

http://momentjs.com/

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

Upvotes: 1

Related Questions