javascript - 在Angular中倒退时间的最佳方法是什么
问题描述
在应用程序中获取最近通知(相对于当前时间)的时间的最佳方法是 5 秒前、10 秒前或 7 小时 32 分钟前?
换句话说,我有一个日期对象(格式2019-03-12T10:05:32.257
),例如从当前时间开始 3 小时 6 分 9 秒前,我想知道是否有一种干净的方法来实现幻数 3、6、9 并显示在html。
解决方案
我认为解决这个问题的更简洁的方法和通用的实现可能是。
- 第一步获取转换为秒的日期对象的差异
然后检查它是否适合
年(除以 31536000)
月(除以 2592000)
天数(除以 86400)
小时(除以 3600)
分钟(除以 60)
function timesAgo(date) {
var seconds = Math.floor((new Date() - date) / 1000); // get the diffrence of date object sent with current date time of the system time
var interval = Math.floor(seconds / 31536000); // divide seconds by seconds in avg for a year to get years
//conditioning based on years derived above
if (interval > 1) {
return interval + " years";
}
interval = Math.floor(seconds / 2592000); // months check similar to years
if (interval > 1) {
return interval + " months";
}
interval = Math.floor(seconds / 86400); // days check similar to above
if (interval > 1) {
return interval + " days";
}
interval = Math.floor(seconds / 3600); // hours check
if (interval > 1) {
return interval + " hours";
}
interval = Math.floor(seconds / 60); // minutes check
if (interval > 1) {
return interval + " minutes";
}
return Math.floor(seconds) + " seconds"; // seconds check at the end
}
var withYears = new Date('August 19, 1999 23:15:30');
var withMonths = new Date('March 19, 2019 23:15:30');
var withDays = new Date('May 1, 2019 23:15:30');
var withPreviousDay = new Date('May 5, 2019 23:15:30');
var withHours = new Date('May 6, 2019 10:15:30');
console.log(timesAgo(withYears));
console.log(timesAgo(withMonths));
console.log(timesAgo(withDays));
console.log(timesAgo(withPreviousDay));
console.log(timesAgo(withHours));
更简单的方法如果您使用 Angular 和 Moment 是为了使用fromNow()
功能 -链接
console.log(moment([2007, 0, 29]).fromNow(true)); // 12 years
console.log(moment([2007, 0, 29]).fromNow()); // 12 years ago
<script data-require="moment.js@*" data-semver="2.18.0" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.0/moment.min.js"></script>
如果您需要 Angular Pipe,请检查 this times-ago-pipe
推荐阅读
- asp.net-mvc - 为什么路由器总是使用路由参数的默认值,而不是提供的?
- javascript - 使用 Javascript 检索 TD 锚点的 html 表格内容
- .net - 使用 ajax 和 .NET Web 应用程序跨域
- c++ - 使用 SendMessage() 的鼠标单击未移交给窗口
- linux - 在 glibc 的 malloc 中使用 POSIX 信号量
- jquery - jQuery 和 Giphy - 下载后设置背景图像
- mysql - 使用 Roll Up 合并无法正常工作(MySql)
- javascript - 当一个数字在 JS 中有 X 个数字时,使用 toExponential() 定义
- python-3.x - 如何在熊猫中选择全天 24 小时的日期?
- excel - 如何在excel中获取调用函数的值