我有一个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"
用一些糖和现代语法来扩展肖恩伟大而简洁的回答:
// 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
已经有了一个叫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())