使用JavaScript中的时间跨度 [英] Work with a time span in Javascript

查看:184
本文介绍了使用JavaScript中的时间跨度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

已经使用Date.js,但如果需要,也可以使用另一个库。

Using Date.js already, but can also use another library if necessary.

不知道使用时间增量的最佳方法是什么。具体来说,我想显示从现在到过去的日期时间之间的时间。

Not sure what is the best way to work with time deltas. Specifically, I want to display the time that has elapsed between now and a past date-time.

所以我需要这样做:

var elapsed_time = new Date() - pastDate;
pastDate.toString('days-hours-minutes-seconds');

得到它主要使用Date.js,但问题是现在我正在使用日期对象而不是时间段,所以应该是23小时的时间跨度是日期第一次的23小时后:

Gotten it to mostly work using Date.js, but the problem is now I'm working with a Date object and not a timespan, so what should be an 23 hour time span is instead 23 hours after the Date's very first time:


var result = (new Date()) - past_date;
"result" is the number (probably milliseconds): 15452732




var result = (new Date() - past_date
"result" is a date from 1969: Wed Dec 31 1969 23:17:32

什么我需要的是:


0 days 23 hours 17 minutes and 32 seconds

任何想法?

推荐答案

听起来像你需要 moment.js

例如

moment().subtract('days', 6).calendar();

=>上星期日8:23 PM

=> last Sunday at 8:23 PM

moment().startOf('hour').fromNow();

=> 26分钟前

编辑:

纯JS日期差异计算:

var date1 = new Date("7/Nov/2012 20:30:00");
var date2 = new Date("20/Nov/2012 19:15:00");

var diff = date2.getTime() - date1.getTime();

var days = Math.floor(diff / (1000 * 60 * 60 * 24));
diff -=  days * (1000 * 60 * 60 * 24);

var hours = Math.floor(diff / (1000 * 60 * 60));
diff -= hours * (1000 * 60 * 60);

var mins = Math.floor(diff / (1000 * 60));
diff -= mins * (1000 * 60);

var seconds = Math.floor(diff / (1000));
diff -= seconds * (1000);

document.write(days + " days, " + hours + " hours, " + mins + " minutes, " + seconds + " seconds");

这篇关于使用JavaScript中的时间跨度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆