gpt4 book ai didi

javascript - Datejs 获取日期之间的差异

转载 作者:行者123 更新时间:2023-11-30 13:18:17 26 4
gpt4 key购买 nike

所以这就是我的目标,我想得到一个特定日期是多久以前的一个非常可读的字符串。类似于:“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;
}

显然这并不完美,无法处理闰年之类的问题,但它应该能让您明白这一点。

关于javascript - Datejs 获取日期之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11216536/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com