Javascript返回两个日期之间的天数,小时,分钟,秒数 [英] Javascript return number of days,hours,minutes,seconds between two dates

查看:159
本文介绍了Javascript返回两个日期之间的天数,小时,分钟,秒数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有人可以链接我一些教程,我可以找到如何在2个unix datetimes之间的JavaScript中返回天,小时,分钟,秒数?



我有:

  var date_now = unixtimestamp; 
var date_future = unixtimestamp;

我想返回(live)从date_now剩下多少天,几小时,几分钟到date_future。

解决方案

只需弄清楚差异(不要忘记JS时间戳实际上是以毫秒为单位),分解该值:

  //获取时间之间的总秒数
var delta = Math.abs(date_future - date_now )/ 1000;

//计算(减)整天
var days = Math.floor(delta / 86400);
delta - = days * 86400;

//计算(减)整个小时
var hours = Math.floor(delta / 3600)%24;
delta - =小时* 3600;

//计算(并减去)整个分钟
var minutes = Math.floor(delta / 60)%60;
delta - = minutes * 60;

//剩下的是秒
var seconds = delta%60; //理论上不需要模块

编辑只是意识到原来的代码返回了总的小时数等,而不是整天计算剩余的小时数。


Does anyone can link me to some tutorial where I can find out how to return days , hours , minutes, seconds in javascript between 2 unix datetimes?

I have:

var date_now = unixtimestamp;
var date_future = unixtimestamp;

I would like to return (live) how many days,hours,minutes,seconds left from the date_now to the date_future.

解决方案

Just figure out the difference in seconds (don't forget JS timestamps are actually measured in milliseconds) and decompose that value:

// get total seconds between the times
var delta = Math.abs(date_future - date_now) / 1000;

// calculate (and subtract) whole days
var days = Math.floor(delta / 86400);
delta -= days * 86400;

// calculate (and subtract) whole hours
var hours = Math.floor(delta / 3600) % 24;
delta -= hours * 3600;

// calculate (and subtract) whole minutes
var minutes = Math.floor(delta / 60) % 60;
delta -= minutes * 60;

// what's left is seconds
var seconds = delta % 60;  // in theory the modulus is not required

EDIT code adjusted because I just realised that the original code returned the total number of hours, etc, not the number of hours left after counting whole days.

这篇关于Javascript返回两个日期之间的天数,小时,分钟,秒数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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