0

I am trying to convert a unix time stamp to a datetime object using javascript but am getting a strange output.

The unix timestamps I'm using are 1420243200000 and 1420272000000. My javascript code looks like this:

function timeConverter(UNIX_timestamp){
  // var a = new Date(UNIX_timestamp*1000);
  // var year = a.getFullYear();
  // var month = a.getMonth()+1;
  // var date = a.getDate();
  // var hour = a.getHours();
  // var min = "0" + a.getMinutes();
  // var sec = "0" + a.getSeconds();
  // var time = date + ' ' + month + ' ' + year + ' ' + hour + ':' + min.substr(-2) + ':' + sec.substr(-2) ;
  // return time;
  var myDate = new Date( UNIX_timestamp *1000);
  time = myDate.toLocaleString();
  return time;
}

Neither the commented or uncommented attempts produce the correct date. I keep getting 9/18/46975, 6:00:00 PM and 8/17/46976, 2:00:00 AMas the answers and I can't figure out what's going wrong.

0

2 Answers 2

2

Your timestamp appears to already be in milliseconds. Don't multiply with 1000.

Calling it "UNIX_timestamp" is misleading. Unix timestamp is seconds elapsed since epoch. Timestamps from JS functions (like Date.now() and +new Date()) are milliseconds elapsed since epoch.

Sign up to request clarification or add additional context in comments.

3 Comments

When I don't multiply by 1000 then I get Invalid Date as the result.
@kdubs That's because your variable is potentially a string. Try checking.
Ahhh. It was a string. Fixed it by using var timestamp = parseInt(UNIX_string,10); Thanks!
0

try myDate = new Date(1420243200000);

From the documentation https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

Call the constructor new Date(value);. Where value is "Integer value representing the number of milliseconds since 1 January 1970 00:00:00 UTC (Unix Epoch)."

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.