计算从现在到第二天的精确小时之间的剩余时间

时间:2019-06-03 08:53:54

标签: javascript date time

使用 Javascript 从现在到01:00(上午)的第二天之间剩余的分钟,最简洁,最高效的方法是什么?

然后,一旦当前时间在01:00之后,我就开始计算与下一个时间的差。

4 个答案:

答案 0 :(得分:3)

在javascript中,可以像这样提供指定的日期

var date1 = new Date('June 6, 2019 03:24:00');

或者可以这样指定

var date2 = new Date('2019-6-6T03:24:00');

javascript可以自然地减去2个日期

console.log(date1 - date2);
//expected 0;

使用此方法将输出以毫秒为单位的日期差, 要获取分钟数,您需要将该值除以60000;

如此

var futureTime = new Date('2019-06-06T07:24:00');
//there must be a 0 infront of 1 digit numbers or it is an invalid date
var now = new Date();
var difference = (futureTime - now) / 60000;
//get minutes by dividing by 60000
//doing Date() with no arguments returns the current date

在此处了解有关javascript Date对象的更多信息 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

答案 1 :(得分:2)

let now = new Date();
let next1am = new Date();
next1am.setHours(1, 0, 0, 0); // same as now, but at 01:00:00.000
if (next1am < now) next1am.setDate(next1am.getDate() + 1); // bump date if past
let millisecondDiff = next1am - now;
let minuteDiff = Math.floor(millisecondDiff / 1000 / 60);

答案 2 :(得分:0)

您可以在moment.js这里

var current = new Date()
var end = new Date(start.getTime() + 3600*60)// end time to calculate diff

var minDiff = end - start; // in millisec

答案 3 :(得分:0)

您可以使用纯JavaScript进行计算:

let today = new Date();
let [y,M,d,h,m,s] = '2019-06-04 05:00:11'.split(/[- :]/);
let yourDate = new Date(y,parseInt(M)-1,d,h,parseInt(m)+30,s);
let diffMs = (yourDate - today);
let diffDays = Math.floor(diffMs / 86400000); // days
let diffHrs = Math.floor((diffMs % 86400000) / 3600000); // hours
let diffMins = (diffDays * 24 * 60) 
               +  (diffHrs *60) 
               +  Math.round(((diffMs % 86400000) % 3600000) / 60000); // The overall result
                                                                       // in minutes

另外,请避免将内置解析器用于任何非标准格式,例如在Safari中,新的Date(“ 2019-04-22 05:00:11”)返回无效的日期。您甚至不应该使用标准化格式,因为对于某些格式,您仍然会得到意想不到的结果。 Why does Date.parse give incorrect results?