我尝试获取形式为'018-09-06T15:06:44.091Z‘的字符串,然后从中减去Date.now(),然后将其转换为天、小时、分钟或秒前的字符串。例如,我得到上面的字符串,然后是:var date = Date.now() - new Date('018-09-06T15:06:44.091Z')。这给了我一个数字:697850577。我需要将这个数字转换为一个字符串,该字符串读取'3 days ago'或'30 seconds ago',基于自'018-09-06T15:06:44.091Z'以来所经过的时间。我不能使用moment.js或任何其他库。我只能使用Angular.JS 1.7和/或vanilla JS。
目前的实现是有效的,但必须有比这更好的方法:
function conversions() {
notif.rollupList.rollups.forEach(function (rollup) {
rollup.type = getChangeType(rollup.type);
rollup.modifiedAt = convertDate(rollup.modifiedAt)
})
}
// Converts the date to 'something something ago'
function convertDate(dateString) {
var seconds = Math.floor((Date.now() - new Date(dateString)) /
1000);
if (seconds >= 60) {
var minutes = Math.floor(seconds / 60);
if (minutes >= 60) {
var hours = Math.floor(minutes / 60);
if (hours >= 24) {
var days = Math.floor(hours / 24);
if (days > 1) {
return days.toString() + ' days ago'
} else {
return days.toString() + ' day ago'
}
} else {
if (hours > 1) {
return hours.toString() + ' hours ago'
} else {
return hours.toString() + ' hour ago'
}
}
} else {
if (minutes > 1) {
return minutes.toString() + ' minutes ago'
} else {
return minutes.toString() + ' minute ago'
}
}
} else {
if (second > 1) {
return seconds.toString() + ' seconds ago'
} else {
return seconds.toString() + ' second ago'
}
}
}提前感谢您的帮助。
https://stackoverflow.com/questions/52336566
复制相似问题