all posts

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

Published to Blog on 15 Nov 2010

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()

 

 


Dan Hounshell
Web geek, nerd, amateur maker. Likes: apis, node, mobile, motorcycles, watches, food, Nashville, Savannah, Cincinnati and family. Dislikes: mean people
Dan Hounshell on Twitter