所以这是我的目标,我想知道某个日期多久以前是一个可读性很强的字符串。类似于:'4 天 3 小时前'。我正在使用 datejs,并且我的两个日期目前都是纪元。
我知道我可以从另一个时期减去一个时期,取差值,然后手动计算要输出的字符串。但这感觉就像 datejs 可以处理的事情。但是,我没有看到任何文档(与此相关的任何 js lib)表达了将日期对象或纪元转换为时间量的方法。
关于如何最好地处理这个问题的任何想法?
更新
让我更清楚。当我说人类可读时,这意味着
- 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