首页 > 解决方案 > 在Angular中倒退时间的最佳方法是什么

问题描述

在应用程序中获取最近通知(相对于当前时间)的时间的最佳方法是 5 秒前、10 秒前或 7 小时 32 分钟前?

换句话说,我有一个日期对象(格式2019-03-12T10:05:32.257),例如从当前时间开始 3 小时 6 分 9 秒前,我想知道是否有一种干净的方法来实现幻数 3、6、9 并显示在html。

标签: javascriptangulartypescript

解决方案


我认为解决这个问题的更简洁的方法和通用的实现可能是。

  1. 第一步获取转换为秒的日期对象的差异
  2. 然后检查它是否适合

    • 年(除以 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


推荐阅读