Unix time javascript [duplicate]

2019-08-29 13:43发布

Possible Duplicate:
Convert a Unix timestamp to time in Javascript

I am trying to return a formatted time from a unix time. The unix time is 1349964180.

If you go to unixtimestamp.com and plug in 1349964180 for Timestamp you will get:

TIME STAMP: 1349964180

DATE (M/D/Y @ h:m:s): 10 / 11 / 12 @ 9:03:00am EST

This is what I want, but in javascript.

So something like:

function convert_time(UNIX_timestamp){
......
......
return correct_format;
}

and then the call: convert_time(1349964180);

and console.log should print: 10 / 11 / 12 @ 9:03:00am EST

3条回答
Juvenile、少年°
2楼-- · 2019-08-29 14:00

Well, first of all you need to multiply by 1000, because timestamps in JavaScript are measured in milliseconds.

Once you have that, you can just plug it into a Date object and return the formatted datetime. You will probably need a helper function to pad the numbers (function pad(num) {return (num < 10 ? "0" : "")+num;}) and you should use the getUTC*() functions to avoid timezone issues.

查看更多
Bombasti
3楼-- · 2019-08-29 14:13

A UNIX-timestamp is using seconds whereas JavaScript uses milliseconds. So, you have to multiply the value by 1000:

var myDate  = new Date(1349964180 * 1000);
alert (myDate.toGMTString());
查看更多
我欲成王,谁敢阻挡
4楼-- · 2019-08-29 14:14

you could try this

function convert_time(ts) {
   return new Date(ts * 1000) 
}

and call it like so

console.log(convert_time(1349964180));
查看更多
登录 后发表回答