【发布时间】:2020-03-06 21:12:09
【问题描述】:
我在这篇文章中尝试了类似 Andris 的回答:Convert seconds to days, hours, minutes and seconds,但我也需要几年、几个月和几周的时间。
我正在运行这个
getDateStrings() {
console.log(req_creation_date);
const today = new Date();
const creation_date = new Date('2020-01-06T20:24:00.000Z');
const creation_date_diff = Math.abs(today.getTime() - creation_date.getTime());
const creation_date_diffDays = Math.ceil((creation_date_diff / 1000));
console.log(creation_date_diffDays);
const creation_date_diffDays_days = Math.ceil((creation_date_diff / (1000 * 3600 * 24)) - 1);
console.log(creation_date_diffDays_days);
const y = Math.floor(creation_date_diffDays / (31536000));
const ms = Math.floor(creation_date_diffDays % (3600 * 24 * 7 * 4.34524 * 12) / 2592000);
const w = Math.floor(creation_date_diffDays % (3600 * 24 * 7 * 4.34524) / 604800);
const d = Math.floor(creation_date_diffDays % (3600 * 24 * 7) / 86400);
const h = Math.floor(creation_date_diffDays % (3600 * 24) / 3600);
const m = Math.floor(creation_date_diffDays % 3600 / 60);
const s = Math.floor(creation_date_diffDays % 60);
const yDisplay = y > 0 ? y + (y === 1 ? ' year, ' : ' years, ') : '';
const msDisplay = ms > 0 ? ms + (ms === 1 ? ' month, ' : ' months, ') : '';
const wDisplay = w > 0 ? w + (w === 1 ? ' week, ' : ' weeks, ') : '';
const dDisplay = d > 0 ? d + (d === 1 ? ' day, ' : ' days, ') : '';
const hDisplay = h > 0 ? h + (h === 1 ? ' hour, ' : ' hours, ') : '';
const mDisplay = m > 0 ? m + (m === 1 ? ' minute, ' : ' minutes, ') : '';
const sDisplay = s > 0 ? s + (s === 1 ? ' second ' : ' seconds') : '' ;
console.log(yDisplay, msDisplay, wDisplay, dDisplay + hDisplay + mDisplay + sDisplay);
}
从 2020 年 6 月 6 日到今天已经过去了 60 天。
返回“2 个月,4 周,4 天,21 分钟,10 秒”什么问题,应该是“2 个月,21 分钟,10 秒”
我不知道自己做错了什么,我也在尝试 2020 年 1 月 15 日。 51 天过去了,但它返回“1 个月、2 周、2 天、41 分钟、43 秒”总共 46 天而不是 51 天,因为它应该是“1 个月、3 周、0 天、41 分钟, 43 秒”
非常感谢!
【问题讨论】:
-
将秒转换为月是一个问题,因为它们可能是 {28, 30, 31} 天之一。要获得准确的转换,您需要准确计算秒数的转换时间。
-
@BryanOfEarth 这应该不是问题,因为我不在乎一个月是 31 天还是 28 天,我指定的是一个月有多少天(30 天)。如果两个日期之间的差异较大,则为 7 天。它不应显示天数,例如 8 天,而应显示(1 周零 1 天)之类的内容。
-
请,请,请不要尝试滚动您自己的日期/时间处理代码。有许多可用的库可以为您处理这个问题,moment.js 是比较知名的库之一。
-
我整天都在努力解决这个问题,我来这里寻求帮助,我得到一个 -1 = / ...我正在查看 moment.js 但我仍然没有找到合适的读取 ISO 格式和使用 .fromNow () 函数的方法你建议的帖子没有给我我正在寻找的答案(我已经阅读了所有这些)
标签: javascript angular typescript