所以这是我的目标,我想确定某个日期是多久以前可读的字符串。类似于:“ 4天3小时前”。我正在使用datejs,目前我的两个日期都作为时代。
我知道我可以从另一个减去一个纪元,取其差值,然后手动计算要输出的字符串。但这感觉就像datejs可以处理的。但是,我看不到任何文档(涉及任何js库)来表达将日期对象或时期转换为一定时间的方法。
关于如何最好地处理的任何想法?
更新
让我更加清楚。当我说人类可读的意思是
1天前是“昨天”
2天前是'2天前'
30秒前是“现在”
1年3天12秒钟之前是'1年前'
我最终做了什么
prettyAgo = (ago) ->
ago = ago.getTime() if typeof ago is 'object'
diff = ((new Date()).getTime() - ago) / 1000
dayDiff = Math.floor(diff / 86400)
return false if isNaN(dayDiff) or dayDiff < 0
writer = ''
if dayDiff is 0
if diff < 1 then writer = 'just now'
else if diff < 60 then writer = Math.floor(diff)+' seconds ago'
else if diff < 120 then writer = '1 minute ago'
else if diff < 3600 then writer = Math.floor(diff / 60)+' minutes ago'
else if diff < 7200 then writer = '1 hour ago'
else if diff < 86400 then writer = Math.floor(diff / 3600)+' hours ago'
else if dayDiff is 1 then writer = 'yesterday'
else if dayDiff < 7 then writer = dayDiff+' days ago'
else if dayDiff is 7 then writer = '1 week ago'
else if dayDiff < 31 then writer = Math.ceil( dayDiff / 7 )+' weeks ago'
else writer = new Date(ago).toString 'MMM yyyy'
return writer
最佳答案
DateJS通过包含一个称为TimeSpan的类(在time.js中定义,而不在基本JS文件中定义)来处理此问题,该类为您进行计算。它不进行格式化,因此您需要这样的内容:
function showDiff(date1, date2) {
var diff, rv, yrs;
diff = new TimeSpan(date2 - date1);
if (diff.days > 0) {
// A day or more difference
if (diff.days === 1) {
rv = "yesterday";
}
else if (diff.days >= 365) {
yrs = diff.days / 365;
if (yrs === 1) {
rv = "1 year ago";
}
else {
rv = yrs + " years ago";
}
}
else {
rv = diff.days + " ago";
}
}
else {
// Less than 1 day difference
if (diff.hours > 0) {
if (diff.hours === 1) {
rv = "1 hour ago";
}
else {
rv = diff.hours + " hours ago";
}
}
else if (diff.minutes > 0) {
if (diff.minutes === 1) {
rv = "1 minute ago";
}
else {
rv = diff.minutes + " minutes ago";
}
}
else {
rv = "just now";
}
return rv;
}
显然,这并不完美,不能解决leap年和其他所有问题,但这应该可以为您带来灵感。