[英]How to turn a Date into a 'days, or hours, or seconds ago' string?
我正在尝试采用'018-09-06T15:06:44.091Z'形式的字符串,然后从中减去Date.now(),然后将其转换为几天,几小时,几分钟或几秒钟前的字符串。 例如,我得到上面的字符串,然后: var date = Date.now() - new Date('018-09-06T15:06:44.091Z')
。 那给了我一个数字: 697850577
。 我需要根据自'018-09-06T15:06:44.091Z'
以来已经流逝了多少时间,将该数字转换为读为'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'
}
}
}
在此先感谢您的帮助。
timeSince=(date)=>{ let seconds = Math.floor((new Date() - date) / 1000); let interval = Math.floor(seconds / 31536000); if (interval > 1) { return interval + " years"; } interval = Math.floor(seconds / 2592000); if (interval > 1) { return interval + " months"; } interval = Math.floor(seconds / 86400); if (interval > 1) { return interval + " days"; } interval = Math.floor(seconds / 3600); if (interval > 1) { return interval + " hours"; } interval = Math.floor(seconds / 60); if (interval > 1) { return interval + " minutes"; } return Math.floor(seconds) + " seconds"; } let aDay = 24*60*60*1000 console.log(timeSince(new Date(Date.now()-aDay))); console.log(timeSince(new Date(Date.now()-aDay*2)));
我花了1个快速的Google搜索和一个快速的JS小提琴测试网格才能找到答案,因为我喜欢ES6。 这是正确的选择还是您想要的效率取决于您。 原始帖子-> 如何格式化从xxx开始的时间,例如“ 4分钟前”,类似于Stack Exchange网站 <-查找答案是成为开发人员的一部分,也是一个有趣的过程。 做你的研究:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.