Javascript 将 UTC Epoch 转换为本地日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4631928/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert UTC Epoch to local date
提问by Shane Reustle
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.
我一直在与这个斗争一段时间。我正在尝试将纪元转换为日期对象。纪元以UTC格式发送给我。每当您通过new Date()
一个纪元时,它都会假定它是本地纪元。我尝试创建一个 UTC 对象,然后使用setTime()
将其调整到适当的时代,但似乎唯一有用的方法是toUTCString()
字符串对我没有帮助。如果我将该字符串传递给一个新日期,它应该注意到它是 UTC,但它不是。
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.
我的下一次尝试是尝试获取本地当前纪元和 UTC 当前纪元之间的差异,但我也无法得到它。
new Date( new Date().toUTCString() ).getTime() - new Date().getTime()
It's only giving me very small differences, under 1000, which is in milliseconds.
它只给我很小的差异,低于 1000,以毫秒为单位。
Any suggestions?
有什么建议?
回答by user1030503
I think I have a simpler solution -- set the initial date to the epoch and add UTC units. Say you have a UTC epoch var stored in seconds. How about 1234567890
. To convert that to a proper date in the local time zone:
我想我有一个更简单的解决方案——将初始日期设置为纪元并添加 UTC 单位。假设您有一个以秒为单位存储的 UTC 纪元变量。怎么样1234567890
。要将其转换为本地时区中的正确日期:
var utcSeconds = 1234567890;
var d = new Date(0); // The 0 there is the key, which sets the date to the epoch
d.setUTCSeconds(utcSeconds);
d
is now a date (in my time zone) set to Fri Feb 13 2009 18:31:30 GMT-0500 (EST)
d
现在是一个日期(在我的时区)设置为 Fri Feb 13 2009 18:31:30 GMT-0500 (EST)
回答by djechlin
It's easy, new Date()
just takes milliseconds, e.g.
这很简单,new Date()
只需要几毫秒,例如
new Date(1394104654000)
> Thu Mar 06 2014 06:17:34 GMT-0500 (EST)
回答by Gus
回答by logic8
Epoch time is in secondsfrom Jan. 1, 1970. date.getTime()
returns millisecondsfrom Jan. 1, 1970, so.. if you have an epoch timestamp, convert it to a javascript timestamp by multiplying by 1000.
纪元时间是从 1970 年 1 月 1 日开始的秒数。date.getTime()
返回从 1970 年 1 月 1 日开始的毫秒数,因此..如果您有纪元时间戳,请将其乘以 1000 将其转换为 javascript 时间戳。
function epochToJsDate(ts){
// ts = epoch timestamp
// returns date obj
return new Date(ts*1000);
}
function jsDateToEpoch(d){
// d = javascript date obj
// returns epoch timestamp
return (d.getTime()-d.getMilliseconds())/1000;
}
回答by chris
function ToLocalDate (inDate) {
var date = new Date();
date.setTime(inDate.valueOf() - 60000 * inDate.getTimezoneOffset());
return date;
}
回答by not2qubit
To convert the current epoch time in [ms] to a 24-hour time. You might need to specify the option to disable 12-hourformat.
以 [ms] 为单位将当前纪元时间转换为 24 小时制。您可能需要指定禁用 12 小时格式的选项。
$ node.exe -e "var date = new Date(Date.now()); console.log(date.toLocaleString('en-GB', { hour12:false } ));"
2/7/2018, 19:35:24
or as JS:
或作为 JS:
var date = new Date(Date.now());
console.log(date.toLocaleString('en-GB', { hour12:false } ));
// 2/7/2018, 19:35:24
console.log(date.toLocaleString('en-GB', { hour:'numeric', minute:'numeric', second:'numeric', hour12:false } ));
// 19:35:24
Note:The use of en-GB
here, is just a (random) choice of a place using the 24 hour format, it is not your timezone!
注意:en-GB
这里的使用,只是一个(随机)选择一个使用 24 小时格式的地方,它不是你的时区!
回答by garryp
Epoch time (i.e. Unix Epoch time) is nearly always the number of secondsthat have expired since 1st Jan 1970 00:00:00 (UTC time), not the number of millisecondswhich some of the answers here have implied.
大纪元时间(即Unix纪元时间)几乎总是数量秒自1970年1月1日00:00:00(UTC时间)已经过期的,而不是数毫秒其中一些在这里的答案已经暗示。
https://en.wikipedia.org/wiki/Unix_time
https://en.wikipedia.org/wiki/Unix_time
Therefore, if you have been given a Unix Epoch time value it will probably be in seconds, and will look something like 1547035195
. If you want to make this human readable in JavaScript, you need to convert the value to milliseconds, and pass that value into the Date(value)
constructor, e.g.:
因此,如果您获得了 Unix Epoch 时间值,它可能以秒为单位,并且看起来像1547035195
. 如果你想在 JavaScript 中使这个人类可读,你需要将值转换为毫秒,并将该值传递给Date(value)
构造函数,例如:
const unixEpochTimeMS = 1547035195 * 1000;
const d = new Date(unixEpochTimeMS);
// Careful, the string output here can vary by implementation...
const strDate = d.toLocaleString();
You don't need to do the d.setUTCMilliseconds(0)
step in the accepted answer because the JavaScript Date(value)
constructor takes a UTCvalue in milliseconds (not a local time).
您不需要执行已d.setUTCMilliseconds(0)
接受答案中的步骤,因为 JavaScriptDate(value)
构造函数采用以毫秒为单位的UTC值(不是本地时间)。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#Syntax
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#Syntax
Also note that you should avoid using the Date(...)
constructor that takes a string datetime representation, this is not recommended (see the link above).
另请注意,您应该避免使用Date(...)
采用字符串日期时间表示的构造函数,这是不推荐的(请参阅上面的链接)。
回答by Sarvar Nishonboev
Addition to the above answer by @djechlin
除了@djechlin的上述答案
d = '1394104654000';
new Date(parseInt(d));
converts EPOCH time to human readable date. Just don't forget that type of EPOCH time must be an Integer.
将 EPOCH 时间转换为人类可读的日期。只是不要忘记 EPOCH 时间的类型必须是整数。
回答by ZagNut
Are you just asking to convert a UTC string to a "local" string? You could do:
您是否只是要求将 UTC 字符串转换为“本地”字符串?你可以这样做:
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);
回答by Darlesson
If you prefer to resolve timestamps and dates conversions from and to UTC and local time without libraries like moment.js, take a look at the option below.
如果您更喜欢在没有诸如 moment.js 之类的库的情况下解决时间戳和日期与 UTC 和本地时间之间的转换,请查看下面的选项。
For applications that use UTC timestamps, you may need to show the date in the browser considering the local timezone and daylight savings when applicable. Editing a date that is in a different daylight savings time even though in the same timezone can be tricky.
对于使用 UTC 时间戳的应用程序,考虑当地时区和夏令时(如果适用),您可能需要在浏览器中显示日期。即使在同一时区,编辑处于不同夏令时的日期也很棘手。
The Number
and Date
extensions below allow you to show and get dates in the timezone of the timestamps. For example, lets say you are in Vancouver, if you are editing a date in July or in December, it can mean you are editing a date in PST or PDT.
下面的Number
和Date
扩展允许您在时间戳的时区中显示和获取日期。例如,假设您在温哥华,如果您正在编辑 7 月或 12 月的日期,则可能意味着您正在编辑 PST 或 PDT 格式的日期。
I recommend you to check the Code Snippet down below to test this solution.
我建议您查看下面的代码片段以测试此解决方案。
Conversions from milliseconds
毫秒级的转换
Number.prototype.toLocalDate = function () {
var value = new Date(this);
value.setHours(value.getHours() + (value.getTimezoneOffset() / 60));
return value;
};
Number.prototype.toUTCDate = function () {
var value = new Date(this);
value.setHours(value.getHours() - (value.getTimezoneOffset() / 60));
return value;
};
Conversions from dates
从日期转换
Date.prototype.getUTCTime = function () {
return this.getTime() - (this.getTimezoneOffset() * 60000);
};
Usage
用法
// Adds the timezone and daylight savings if applicable
(1499670000000).toLocalDate();
// Eliminates the timezone and daylight savings if applicable
new Date(2017, 6, 10).getUTCTime();
See it for yourself
自己看看
// Extending Number
Number.prototype.toLocalDate = function () {
var value = new Date(this);
value.setHours(value.getHours() + (value.getTimezoneOffset() / 60));
return value;
};
Number.prototype.toUTCDate = function () {
var value = new Date(this);
value.setHours(value.getHours() - (value.getTimezoneOffset() / 60));
return value;
};
// Extending Date
Date.prototype.getUTCTime = function () {
return this.getTime() - (this.getTimezoneOffset() * 60000);
};
// Getting the demo to work
document.getElementById('m-to-local-button').addEventListener('click', function () {
var displayElement = document.getElementById('m-to-local-display'),
value = document.getElementById('m-to-local').value,
milliseconds = parseInt(value);
if (typeof milliseconds === 'number')
displayElement.innerText = (milliseconds).toLocalDate().toISOString();
else
displayElement.innerText = 'Set a value';
}, false);
document.getElementById('m-to-utc-button').addEventListener('click', function () {
var displayElement = document.getElementById('m-to-utc-display'),
value = document.getElementById('m-to-utc').value,
milliseconds = parseInt(value);
if (typeof milliseconds === 'number')
displayElement.innerText = (milliseconds).toUTCDate().toISOString();
else
displayElement.innerText = 'Set a value';
}, false);
document.getElementById('date-to-utc-button').addEventListener('click', function () {
var displayElement = document.getElementById('date-to-utc-display'),
yearValue = document.getElementById('date-to-utc-year').value || '1970',
monthValue = document.getElementById('date-to-utc-month').value || '0',
dayValue = document.getElementById('date-to-utc-day').value || '1',
hourValue = document.getElementById('date-to-utc-hour').value || '0',
minuteValue = document.getElementById('date-to-utc-minute').value || '0',
secondValue = document.getElementById('date-to-utc-second').value || '0',
year = parseInt(yearValue),
month = parseInt(monthValue),
day = parseInt(dayValue),
hour = parseInt(hourValue),
minute = parseInt(minuteValue),
second = parseInt(secondValue);
displayElement.innerText = new Date(year, month, day, hour, minute, second).getUTCTime();
}, false);
<link href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.11/semantic.css" rel="stylesheet"/>
<div class="ui container">
<p></p>
<h3>Milliseconds to local date</h3>
<input id="m-to-local" placeholder="Timestamp" value="0" /> <button id="m-to-local-button">Convert</button>
<em id="m-to-local-display">Set a value</em>
<h3>Milliseconds to UTC date</h3>
<input id="m-to-utc" placeholder="Timestamp" value="0" /> <button id="m-to-utc-button">Convert</button>
<em id="m-to-utc-display">Set a value</em>
<h3>Date to milliseconds in UTC</h3>
<input id="date-to-utc-year" placeholder="Year" style="width: 4em;" />
<input id="date-to-utc-month" placeholder="Month" style="width: 4em;" />
<input id="date-to-utc-day" placeholder="Day" style="width: 4em;" />
<input id="date-to-utc-hour" placeholder="Hour" style="width: 4em;" />
<input id="date-to-utc-minute" placeholder="Minute" style="width: 4em;" />
<input id="date-to-utc-second" placeholder="Second" style="width: 4em;" />
<button id="date-to-utc-button">Convert</button>
<em id="date-to-utc-display">Set the values</em>
</div>