某个事件过去了多少时间

时间:2019-03-03 03:45:10

标签: javascript jquery

需要显示信息-某个事件过去了多少时间。

例如:

var event = '2017-04-25 09:20:00';
var datea = new Date(event);
var dateb = new Date();
var diff = Math.abs(dateb.getTime() - datea.getTime());
var days = Math.ceil(diff / (1000 * 3600 * 24));
var hours = Math.ceil(diff / (1000 * 3600));
var mins = Math.ceil(diff / (1000 * 60));
var sec = Math.ceil(diff / (1000));

但这都是dayshours ...等的总值。

我想以这种方式显示信息:

xYears xMonths xDays xHours xMins xSecs前发生的事件

如何以上述方式计算和显示信息?

YearsMonths可以在36530天四舍五入。

此外,信息应该每秒更新一次。

有帮助吗?

1 个答案:

答案 0 :(得分:1)

使用moment.js(这是我所知道的最可靠的日期库),它看起来像这样:

// your date
var event = '2017-04-25 09:20:00';

// Moment objects to compare
var datea = moment(event,"YYYY-MM-DD HH:mm:ss");
var now = moment();

// Find the difference
var diff = now.diff(datea);
var d = moment.duration(diff);

// Resulting object
console.log(d._data);

// Formatting...
$("span").html(d._data.years+" years, "+
               d._data.months+" months, "+
               d._data.days+" days, "+
               d._data.hours+" hours, "+
               d._data.minutes+" minutes, "+
               d._data.seconds+" seconds");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>

<span></span>

寻找这些时刻方法: