295

我有一个Date对象。如何呈现title以下代码段的部分?

<abbr title="2010-04-02T14:12:07">A couple days ago</abbr>

我有另一个图书馆的“相对时间”部分。

我尝试了以下方法:

function isoDate(msSinceEpoch) {

   var d = new Date(msSinceEpoch);
   return d.getUTCFullYear() + '-' + (d.getUTCMonth() + 1) + '-' + d.getUTCDate() + 'T' +
          d.getUTCHours() + ':' + d.getUTCMinutes() + ':' + d.getUTCSeconds();

}

但这给了我:

"2010-4-2T3:19"
4

14 回答 14

535

已经有一个函数叫做toISOString()

var date = new Date();
date.toISOString(); //"2011-12-19T15:28:46.493Z"

如果不知何故,您使用的浏览器不支持它,我已经为您提供了保障:

if (!Date.prototype.toISOString) {
  (function() {

    function pad(number) {
      var r = String(number);
      if (r.length === 1) {
        r = '0' + r;
      }
      return r;
    }

    Date.prototype.toISOString = function() {
      return this.getUTCFullYear() +
        '-' + pad(this.getUTCMonth() + 1) +
        '-' + pad(this.getUTCDate()) +
        'T' + pad(this.getUTCHours()) +
        ':' + pad(this.getUTCMinutes()) +
        ':' + pad(this.getUTCSeconds()) +
        '.' + String((this.getUTCMilliseconds() / 1000).toFixed(3)).slice(2, 5) +
        'Z';
    };

  }());
}

console.log(new Date().toISOString())

于 2011-12-19T15:27:44.850 回答
64

请参阅页面https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference:Global_Objects:Date上的最后一个示例:

/* Use a function for the exact format desired... */
function ISODateString(d) {
    function pad(n) {return n<10 ? '0'+n : n}
    return d.getUTCFullYear()+'-'
         + pad(d.getUTCMonth()+1)+'-'
         + pad(d.getUTCDate())+'T'
         + pad(d.getUTCHours())+':'
         + pad(d.getUTCMinutes())+':'
         + pad(d.getUTCSeconds())+'Z'
}

var d = new Date();
console.log(ISODateString(d)); // Prints something like 2009-09-28T19:03:12Z
于 2010-04-05T15:55:50.420 回答
64

注意:截至 2022 年 3 月,此答案仍在获得支持。moment.js库弃用。这是两个主要的替代方案:LuxonDay.js,其他在弃用链接中提到。

卢克森

Luxon 可以被认为是 Moment 的演变。它由 Moment 的长期撰稿人Isaac Cambron撰写。请阅读为什么 Luxon 存在?以及 Luxon 文档中的For Moment 用户页面。

地区:国际提供时区:国际提供

Day.js

Day.js 旨在成为 Moment.js 的简约替代品,使用类似的 API。它不是直接替代品,但如果您习惯使用 Moment 的 API 并希望快速上手,请考虑使用 Day.js。

区域设置:可以单独导入的自定义数据文件时区:通过插件提供国际

由于大小不同,我使用 Day.js,但 Luxon 更容易处理。


几乎网络上的每个 to-ISO 方法都通过在输出字符串之前应用转换为“Z”ulu 时间 (UTC) 来删除时区信息。浏览器的原生 .toISOString() 也会删除时区信息。

这会丢弃有价值的信息,因为服务器或接收者始终可以将完整的 ISO 日期转换为祖鲁时间或它需要的任何时区,同时仍能获取发送者的时区信息。

我遇到的最佳解决方案是使用Moment.js javascript 库并使用以下代码:

获取带有时区信息和毫秒的当前 ISO 时间

now = moment().format("YYYY-MM-DDTHH:mm:ss.SSSZZ")
// "2013-03-08T20:11:11.234+0100"

now = moment().utc().format("YYYY-MM-DDTHH:mm:ss.SSSZZ")
// "2013-03-08T19:11:11.234+0000"

now = moment().utc().format("YYYY-MM-DDTHH:mm:ss") + "Z"
// "2013-03-08T19:11:11Z" <- better use the native .toISOString() 

获取包含时区信息但不包含毫秒的原生 JavaScript Date 对象的 ISO 时间

var current_time = Date.now();
moment(current_time).format("YYYY-MM-DDTHH:mm:ssZZ")

这可以与 Date.js 结合以获取像 Date.today() 这样的函数,然后可以将其结果传递给 moment。

像这样格式化的日期字符串是 JSON 兼容的,并且很适合存储到数据库中。Python 和 C# 似乎很喜欢它。

于 2013-03-08T19:50:01.573 回答
38

提出的问题是精度降低的 ISO格式。瞧:

 new Date().toISOString().slice(0, 19) + 'Z'
 // '2014-10-23T13:18:06Z'

假设需要尾随 Z,否则就省略。

于 2014-10-23T13:19:04.033 回答
17

最短,但不受 Internet Explorer 8 及更早版本支持:

new Date().toJSON()
于 2012-11-08T14:12:56.833 回答
13

如果您不需要支持 IE7,以下是一个很棒的简洁 hack:

console.log(
  JSON.parse(JSON.stringify(new Date()))
)

于 2012-05-03T22:53:46.993 回答
10

我通常不想显示 UTC 日期,因为客户不喜欢在脑海中进行转换。要显示本地ISO 日期,我使用以下函数:

function toLocalIsoString(date, includeSeconds) {
    function pad(n) { return n < 10 ? '0' + n : n }
    var localIsoString = date.getFullYear() + '-'
        + pad(date.getMonth() + 1) + '-'
        + pad(date.getDate()) + 'T'
        + pad(date.getHours()) + ':'
        + pad(date.getMinutes()) + ':'
        + pad(date.getSeconds());
    if(date.getTimezoneOffset() == 0) localIsoString += 'Z';
    return localIsoString;
};

上面的函数省略了时区偏移信息(除非本地时间恰好是 UTC),所以我使用下面的函数来显示单个位置的本地偏移。如果您希望每次都显示偏移量,还可以将其输出附加到上述函数的结果中:

function getOffsetFromUTC() {
    var offset = new Date().getTimezoneOffset();
    return ((offset < 0 ? '+' : '-')
        + pad(Math.abs(offset / 60), 2)
        + ':'
        + pad(Math.abs(offset % 60), 2))
};

toLocalIsoString使用pad. 如果需要,它几乎可以像任何 pad 功能一样工作,但为了完整起见,这是我使用的:

// Pad a number to length using padChar
function pad(number, length, padChar) {
    if (typeof length === 'undefined') length = 2;
    if (typeof padChar === 'undefined') padChar = '0';
    var str = "" + number;
    while (str.length < length) {
        str = padChar + str;
    }
    return str;
}
于 2013-04-23T19:04:38.163 回答
5

toISOString 的问题在于它仅将日期时间指定为“Z”。

ISO-8601 还定义了带有时区差异的日期时间(以小时和分钟为单位),格式为 2016-07-16T19:20:30+5:30(当时区早于 UTC 时)和 2016-07-16T19:20:30-01 :00(当时区落后于 UTC 时)。

我不认为使用另一个插件,moment.js 来完成这么小的任务不是一个好主意,尤其是当你可以用几行代码得到它的时候。

一旦你有了小时和分钟的时区偏移量,你就可以附加到一个日期时间字符串。

我在上面写了一篇博文: http: //usefulangle.com/post/30/javascript-get-date-time-with-offset-hours-minutes

var timezone_offset_min = new Date().getTimezoneOffset(),
  offset_hrs = parseInt(Math.abs(timezone_offset_min / 60)),
  offset_min = Math.abs(timezone_offset_min % 60),
  timezone_standard;

if (offset_hrs < 10)
  offset_hrs = '0' + offset_hrs;

if (offset_min > 10)
  offset_min = '0' + offset_min;

// getTimezoneOffset returns an offset which is positive if the local timezone is behind UTC and vice-versa.
// So add an opposite sign to the offset
// If offset is 0, it means timezone is UTC
if (timezone_offset_min < 0)
  timezone_standard = '+' + offset_hrs + ':' + offset_min;
else if (timezone_offset_min > 0)
  timezone_standard = '-' + offset_hrs + ':' + offset_min;
else if (timezone_offset_min == 0)
  timezone_standard = 'Z';

// Timezone difference in hours and minutes
// String such as +5:30 or -6:00 or Z
console.log(timezone_standard);

于 2017-01-05T10:19:00.423 回答
3

在“T”之后缺少一个“+”

isoDate: function(msSinceEpoch) {
  var d = new Date(msSinceEpoch);
  return d.getUTCFullYear() + '-' + (d.getUTCMonth() + 1) + '-' + d.getUTCDate() + 'T'
         + d.getUTCHours() + ':' + d.getUTCMinutes() + ':' + d.getUTCSeconds();
}

应该这样做。

对于前导零,您可以从这里使用它:

function PadDigits(n, totalDigits) 
{ 
    n = n.toString(); 
    var pd = ''; 
    if (totalDigits > n.length) 
    { 
        for (i=0; i < (totalDigits-n.length); i++) 
        { 
            pd += '0'; 
        } 
    } 
    return pd + n.toString(); 
} 

像这样使用它:

PadDigits(d.getUTCHours(),2)
于 2010-04-04T04:15:16.473 回答
3
function timeStr(d) { 
  return ''+
    d.getFullYear()+
    ('0'+(d.getMonth()+1)).slice(-2)+
    ('0'+d.getDate()).slice(-2)+
    ('0'+d.getHours()).slice(-2)+
    ('0'+d.getMinutes()).slice(-2)+
    ('0'+d.getSeconds()).slice(-2);
}
于 2016-12-01T09:06:55.443 回答
2

我能够以非常少的代码获得低于输出。

var ps = new Date('2010-04-02T14:12:07')  ;
ps = ps.toDateString() + " " + ps.getHours() + ":"+ ps.getMinutes() + " hrs";

输出:

Fri Apr 02 2010 19:42 hrs
于 2017-02-26T04:08:55.193 回答
1

我只会使用这个小扩展来Date- http://blog.stevenlevithan.com/archives/date-time-format

var date = new Date(msSinceEpoch);
date.format("isoDateTime"); // 2007-06-09T17:46:21
于 2010-04-04T11:05:41.827 回答
1
function getdatetime() {
    d = new Date();
    return (1e3-~d.getUTCMonth()*10+d.toUTCString()+1e3+d/1)
        .replace(/1(..)..*?(\d+)\D+(\d+).(\S+).*(...)/,'$3-$1-$2T$4.$5Z')
        .replace(/-(\d)T/,'-0$1T');
}

我在某个地方找到了有关 Stack Overflow 的基础知识(我相信它是其他一些 Stack Exchange 代码打高尔夫球的一部分),并且我对其进行了改进,使其也可以在 Internet Explorer 10 或更早版本上运行。这很丑陋,但它可以完成工作。

于 2015-03-05T15:53:54.357 回答
0

用一些糖和现代语法扩展肖恩的伟大而简洁的答案:

// date.js

const getMonthName = (num) => {
  const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Oct', 'Nov', 'Dec'];
  return months[num];
};

const formatDate = (d) => {
  const date = new Date(d);
  const year = date.getFullYear();
  const month = getMonthName(date.getMonth());
  const day = ('0' + date.getDate()).slice(-2);
  const hour = ('0' + date.getHours()).slice(-2);
  const minutes = ('0' + date.getMinutes()).slice(-2);

  return `${year} ${month} ${day}, ${hour}:${minutes}`;
};

module.exports = formatDate;

然后例如。

import formatDate = require('./date');

const myDate = "2018-07-24T13:44:46.493Z"; // Actual value from wherever, eg. MongoDB date
console.log(formatDate(myDate)); // 2018 Jul 24, 13:44
于 2018-07-24T10:46:42.310 回答