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

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

当前回答

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

其他回答

我可以用非常少的代码得到以下的输出。

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

输出:

Fri Apr 02 2010 19:42 hrs

一个简短的例子:

console.log(new Date().toISOString().slice(0,19).replace('T', ' '))

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

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

假设后面的Z是需要的,否则就省略。

我通常不希望显示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;
}

toISOString的问题是它只将datetime作为“Z”。

ISO-8601还定义了带小时和分钟时区差异的datetime,格式为2016-07-16T19:20:30+5:30(当时区在UTC之前时)和2016-07-16T19:20:30-01:00(当时区在UTC之后时)。

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

一旦有了以小时和分钟为单位的时区偏移量,就可以追加到datetime字符串。

我为此写了一篇博客: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);