Convert UTC Epoch to local date

2019-01-01 01:59发布

I have been fighting with this for a bit now. I’m trying to convert epoch to a date object. The epoch is sent to me in UTC. Whenever you pass new Date() an epoch, it assumes it’s local epoch. I tried creating a UTC object, then using setTime() to adjust it to the proper epoch, but the only method that seems useful is toUTCString() and strings don’t help me. If I pass that string into a new date, it should notice that it’s UTC, but it doesn’t.

new Date( new Date().toUTCString() ).toLocaleString()

My next attempt was to try to get the difference between local current epoch and UTC current epoch, but I wasn’t able to get that either.

new Date( new Date().toUTCString() ).getTime() - new Date().getTime()

It’s only giving me very small differences, under 1000, which is in milliseconds.

Any suggestions?

13条回答
千与千寻千般痛.
2楼-- · 2019-01-01 02:08

And just for the logs, I did this using Moment.js library, which I was using for formatting anyway.

moment.utc(1234567890000).local()
>Fri Feb 13 2009 19:01:30 GMT-0430 (VET)
查看更多
何处买醉
3楼-- · 2019-01-01 02:14

It's easy, new Date() just takes milliseconds, e.g.

new Date(1394104654000)
> Thu Mar 06 2014 06:17:34 GMT-0500 (EST)
查看更多
无与为乐者.
4楼-- · 2019-01-01 02:17
 function ToLocalDate (inDate) {
    var date = new Date();
    date.setTime(inDate.valueOf() - 60000 * inDate.getTimezoneOffset());
    return date;
}
查看更多
伤终究还是伤i
5楼-- · 2019-01-01 02:21

Are you just asking to convert a UTC string to a "local" string? You could do:

var utc_string = '2011-09-05 20:05:15';
var local_string = (function(dtstr) {
    var t0 = new Date(dtstr);
    var t1 = Date.parse(t0.toUTCString().replace('GMT', ''));
    var t2 = (2 * t0) - t1;
    return new Date(t2).toString();
})(utc_string);
查看更多
长期被迫恋爱
6楼-- · 2019-01-01 02:25

First convert it to String and then replace the timezone text.

function convertUnixTime(time) {
  return new Date(time*1000).toString().replace("GMT+0530 (Sri Lanka Standard Time)","");
}
查看更多
旧人旧事旧时光
7楼-- · 2019-01-01 02:26

EDIT

var utcDate = new Date(incomingUTCepoch);
var date = new Date();
date.setUTCDate(utcDate.getDate());
date.setUTCHours(utcDate.getHours());
date.setUTCMonth(utcDate.getMonth());
date.setUTCMinutes(utcDate.getMinutes());
date.setUTCSeconds(utcDate.getSeconds());
date.setUTCMilliseconds(utcDate.getMilliseconds());

EDIT fixed

查看更多
登录 后发表回答