我写了一个函数来将UTC时间反转到当地时间
function utcToLocal(utc){
var t = new Date(Number(utc));
d = [t.getFullYear(), t.getMonth(), t.getDate()].join('/');
d += ' ' + t.toLocaleTimeString();
return d;
}
Run Code Online (Sandbox Code Playgroud)
但我不能确认这段代码是对的吗?
您应该能够将UTC时间戳转换为本地日期,只需减去本地偏移量(以分钟为单位),因此:
function utcToLocal(utc){
// Create a local date from the UTC string
var t = new Date(Number(utc));
// Get the offset in ms
var offset = t.getTimezoneOffset()*60000;
// Subtract from the UTC time to get local
t.setTime(t.getTime() - offset);
// do whatever
var d = [t.getFullYear(), t.getMonth(), t.getDate()].join('/');
d += ' ' + t.toLocaleTimeString();
return d;
}
Run Code Online (Sandbox Code Playgroud)
我在哪里,偏移是-600,所以我需要从UTC时间减去-36,000,000毫秒(实际上增加36,000,000毫秒).
我可能误解了这个问题.
javascript日期实例的内部值是UTC时间片段(以毫秒为单位).因此,如果utc是这样的时间(例如2012-08-19T00:00:00Z是1345334400000),则OP将基于该值创建日期实例, toLocaleTimeString并将显示所提供的UTC时间的本地时间的实现相关字符串.
因此,如果当地时区偏移量为-6小时,则alert(new Date(1345334400000)))显示类似于星期六2012年8月18日18:00:00 GMT-600.
我假设OP想要将当地时间设置为UTC时间,例如2012-08-19T00:00:00Z将成为2012-08-19T00:00:00本地时间.