Wrong date from timestamp

I have a problem which can't solve by myself.

Here is timestamp 1308085200 taken from my website database. It represents 2011-06-15 12:00:00

Here is javascript code which I use to "fetch" date in human readable format.

var date    = new Date(1308085200 * 1000);
var year    = date.getFullYear();
var month   = date.getMonth();
var day     = date.getDate();
var hour    = date.getUTCHours();
var minute  = date.getUTCMinutes();
var seconds = date.getUTCSeconds();

The problem is that I get wrong results. For example the code above shows 2011-5-15 21:0:0 instead of 2011-06-15 12:00:00

What I do wrong and how to fix that ?

Answers:

Answer

JavaScript's Date::getMonth() returns a zero-based integer from 0 to 11 which is why your date is showing May instead of June.

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/getMonth

Update

As for the time portion, this is what I get (AEST)

var d = new Date(1308085200000); // Wed Jun 15 07:00:00 GMT+1000 (EST)
d.toUTCString() // Tue, 14 Jun 2011 21:00:00 GMT
d.getUTCFullYear() // 2011
d.getUTCMonth() // 5
d.getUTCDate() // 14
d.getUTCHours() // 21
d.getUTCMinutes() // 0
d.getUTCSeconds() // 0

Looks like your timestamp is actually not what you think it is.

Answer

Well, JavaScript's getMonth() function sucks and starts with 0 for January. You have to add one.

Maybe you want to use date js, since it fixes some of these problems.

Answer

The date and time can vary dependent on the timezone you're in. That's why in my zone (GMT+2000) new Date(1308085200*1000) displays Tue Jun 14 2011 23:00:00 GMT+0200 (W. Europe Daylight Time). Check this reference for everything you always wanted to know about dates in javascript

Regarding formatting (leading zero's etc.), maybe this jsfiddle can help you?

Answer

Try this:

 function timeConverter(createdAt) {
  var date = new Date(createdAt);
  date.toUTCString()
  var year = date.getUTCFullYear();
  var month = date.getUTCMonth()+1;
  var day = date.getUTCDate();
  return day+"-"+month+"-"+year;
}

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.