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

当前回答

我想我找到了一个更好的解决方案:

根据维基页面,加拿大使用ISO 8601作为官方日期格式,因此我们可以安全地使用它。

console.log(new Date("2022-12-19 00:43:00 GMT+0100").toISOString().split("T")[0]); // result in '2022-12-18' console.log(new Date("2022-12-19 00:43:00 GMT+0100").toLocaleDateString("en-CA")); // result in '2022-12-19'

其他回答

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

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

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

一个简短的例子:

console.log(new Date().toISOString().slice(0,19).replace('T', ' '))
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);
}

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

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

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

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

输出:

Fri Apr 02 2010 19:42 hrs