我有一个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"

当前回答

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

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

输出:

Fri Apr 02 2010 19:42 hrs

其他回答

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或更早的版本上运行。虽然很丑,但能完成任务。

已经有了一个叫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())

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

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

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', ' '))