347

我已经和这个斗争了一段时间。我正在尝试将纪元转换为日期对象。纪元以 UTC 格式发送给我。每当您通过new Date()一个纪元时,它都会假定它是本地纪元。我尝试创建一个 UTC 对象,然后使用setTime()将其调整到适当的时代,但似乎有用的唯一方法是toUTCString()字符串对我没有帮助。如果我将该字符串传递给新日期,它应该会注意到它是 UTC,但事实并非如此。

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

我的下一个尝试是尝试获取本地当前纪元和 UTC 当前纪元之间的差异,但我也无法得到。

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

它只给了我非常小的差异,低于 1000,以毫秒为单位。

有什么建议么?

4

16 回答 16

578

我想我有一个更简单的解决方案——将初始日期设置为纪元并添加 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现在是一个日期(在我的时区)设置为Fri Feb 13 2009 18:31:30 GMT-0500 (EST)

于 2011-11-04T22:00:33.497 回答
309

这很容易,new Date()只需要几毫秒,例如

new Date(1394104654000)
> Thu Mar 06 2014 06:17:34 GMT-0500 (EST)
于 2014-03-06T22:09:46.050 回答
35

仅针对日志,我使用Moment.js库进行了此操作,无论如何我都使用该库进行格式化。

moment.utc(1234567890000).local()
>Fri Feb 13 2009 19:01:30 GMT-0430 (VET)
于 2012-10-19T19:10:02.887 回答
30

纪元时间从 1970 年 1 月 1 日开始以秒为单位。从 1970 年 1 月 1 日开始date.getTime()返回毫秒,所以.. 如果您有纪元时间戳,请将其乘以 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;
   }
于 2012-09-09T20:55:56.860 回答
16
 function ToLocalDate (inDate) {
    var date = new Date();
    date.setTime(inDate.valueOf() - 60000 * inDate.getTimezoneOffset());
    return date;
}
于 2012-01-27T20:36:55.090 回答
9

纪元时间(即 Unix 纪元时间)几乎总是自 1970 年 1 月 1 日 00:00:00(UTC 时间)以来已过期的秒数,而不是此处某些答案所暗示的毫秒

https://en.wikipedia.org/wiki/Unix_time

因此,如果给您一个 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();

您不需要执行d.setUTCMilliseconds(0)已接受答案中的步骤,因为 JavaScriptDate(value)构造函数采用以毫秒为单位的UTC值(不是本地时间)。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#Syntax

另请注意,您应避免使用Date(...)采用字符串日期时间表示的构造函数,不建议这样做(请参阅上面的链接)。

于 2019-01-09T11:59:02.980 回答
5

以 [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

或作为 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

注意:这里的使用en-GB只是(随机)选择一个使用 24 小时格式的地方,它不是您的时区!

于 2018-02-07T19:43:02.833 回答
5

var myDate = new Date( your epoch date *1000);

来源 - https://www.epochconverter.com/programming/#javascript

于 2020-01-27T09:51:41.700 回答
4

除了@djechlin 的上述答案

d = '1394104654000';
new Date(parseInt(d));

将 EPOCH 时间转换为人类可读的日期。只是不要忘记那种类型的 EPOCH 时间必须是整数。

于 2018-12-07T08:34:25.740 回答
4

我发现的最简单的解决方案是:

var timestamp = Date.now(), // returns milliseconds since epoch time
    normalisedTime = new Date(timestamp);

请注意,这没有声明* 1000结尾,new Date(timestamp)因为这(无论如何对我来说!)似乎总是给出错误的日期,即它没有给出 2019 年,而是给出了 51015 年,所以请记住这一点。

于 2019-01-17T13:20:27.997 回答
4

最简单的方法

如果您以毫秒为单位拥有 unix 纪元,在我的情况下 -1601209912824

  1. 将其转换为日期对象,如下所示
const dateObject = new Date(milliseconds)
const humanDateFormat = dateObject.toString() 

输出 -

Sun Sep 27 2020 18:01:52 GMT+0530 (India Standard Time)
  1. 如果您想要 UTC 日期 -
const dateObject = new Date(milliseconds)
const humanDateFormat = dateObject.toUTCString() 
  1. 现在你可以随意格式化了。

于 2020-09-27T13:38:24.013 回答
3

您只是要求将 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);
于 2011-09-06T00:06:14.640 回答
2

编辑

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());

编辑固定

于 2011-01-08T02:04:16.227 回答
2

考虑到,你有epoch_time可用的,

// for eg. epoch_time = 1487086694.213
var date = new Date(epoch_time * 1000); // multiply by 1000 for milliseconds
var date_string = date.toLocaleString('en-GB');  // 24 hour format
于 2017-02-14T16:43:21.207 回答
2

如果您更喜欢在没有像 moment.js 之类的库的情况下解决往返于 UTC 和本地时间的时间戳和日期转换,请查看以下选项。

对于使用 UTC 时间戳的应用程序,您可能需要在浏览器中显示日期,并考虑当地时区和夏令时(如果适用)。即使在同一时区,编辑处于不同夏令时的日期也可能很棘手。

下面的NumberDate扩展允许您在时间戳的时区中显示和获取日期。例如,假设您在温哥华,如果您正在编辑 7 月或 12 月的日期,这可能意味着您正在编辑 PST 或 PDT 中的日期。

我建议您查看下面的代码片段以测试此解决方案。

毫秒级的转换

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;
};

从日期转换

Date.prototype.getUTCTime = function () {
    return this.getTime() - (this.getTimezoneOffset() * 60000);
};

用法

// Adds the timezone and daylight savings if applicable
(1499670000000).toLocalDate();

// Eliminates the timezone and daylight savings if applicable
new Date(2017, 6, 10).getUTCTime();

亲眼看看

// 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>

于 2017-07-29T08:23:31.603 回答
0

@Amjad,好主意,但更好的实现是:

Date.prototype.setUTCTime = function(UTCTimestamp) {
    var UTCDate = new Date(UTCTimestamp);
    this.setUTCFullYear(UTCDate.getFullYear(), UTCDate.getMonth(), UTCDate.getDate());
    this.setUTCHours(UTCDate.getHours(), UTCDate.getMinutes(), UTCDate.getSeconds(), UTCDate.getMilliseconds());
    return this.getTime();
}
于 2011-09-28T05:54:08.563 回答