November 15, 2010

How to convert a 10-digit timestamp in JSON to a Javascript Date

That’s a fairly long title to describe this:

1280296860

I found this value in a field of a JSON response from a web service where I was expecting a date. I’m used to seeing 13 digit timestamps so this date surprised me and looked a little odd.

After some research I found that the 13-digit timestamp that I’ve grown accustomed to seeing and this 10-digit timestamp are both Unix-style timestamps that represent the number of seconds since January 1, 1970 at 00:00:00 GMT. The difference is that the 13-digit timestamps represent the number of milliseconds and the 10-digit timestamps represent the number of seconds.

History lesson finished. How do you convert that to something useful in Javascript?

In the past when faced with a 13-digit timestamp (now knowing it was milliseconds) I would just use the value in the Javascript Date constructor or use the Date.setTime() method:

 
var timestamp = 1280296860145;
var pubDate = new Date(timestamp); 
OR
var pubDate = new Date();
pubDate.setTime(timestamp);

 

But neither of those worked with the 10-digit timestamp, which seems pretty obvious now that I know that the constructor and the setTime method expect milliseconds. So when you are given a 10-digit timestamp you should first convert it from seconds to milliseconds by multiplying by 1000:

 
var timestamp = 1280296860;
var pubDate = new Date(timestamp * 1000); //expects milliseconds
OR
var pubDate = new Date();
pubDate.setTime(timestamp * 1000); //expects milliseconds 

 

After converting to a Javascript Date you can now do something useful, like format it into a string for display:

 
var weekday=new Array("Sun","Mon","Tue","Wed","Thu","Fri","Sat");
var monthname=new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
var formattedDate = weekday[pubDate.getDay()] + ' ' 
                    + monthname[pubDate.getMonth()] + ' ' 
                    + pubDate.getDate() + ', ' + pubDate.getFullYear()

 

 

Comments,

  • Trackbacks,
  • and Pingbacks
blog comments powered by Disqus

 

Trackbacks and Pingbacks


  1. Pingback from Twitter Trackbacks for How to convert a 10-digit timestamp in JSON to a Javascript Date : Digging My Blog [danhounshell.com] on Topsy.com

Shortcuts

Where is Dan?


My Blog
My Blog
Twitter
Twitter
Facebook
Facebook
LinkedIn
LinkedIn
Flickr
Flickr
YouTube
YouTube
Delicious
Delicious
Foursquare
Foursquare
Pinterest
Pinterest
GetGlue
GetGlue
Pintley
Pintley
XBOX Live
XBOX Live
Last.fm
Last.fm
Windows Live
Windows Live
Telligent.com
Telligent
Graffiti CMS on CodePlex
Graffiti CMS
Popular

Recent Posts