Javascript返回两个日期之间的天数,小时数,分钟数,秒数

时间:2021-10-13 21:32:17

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?

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

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.

我想返回(实时)从date_now到date_future的剩余天数,小时数,分钟数。

8 个解决方案

#1


108  

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

只需计算出以秒为单位的差异(不要忘记JS时间戳实际上以毫秒为单位)并分解该值:

// 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.

EDIT代码调整,因为我刚刚意识到原始代码返回总小时数等,而不是整天计算后剩余的小时数。

#2


23  

Here's in javascript: (For example, the future date is New Year's Day)

这里是javascript :(例如,未来的日期是新年)

DEMO (updates every second)

演示(每秒更新)

var dateFuture = new Date(new Date().getFullYear() +1, 0, 1);
var dateNow = new Date();

var seconds = Math.floor((dateFuture - (dateNow))/1000);
var minutes = Math.floor(seconds/60);
var hours = Math.floor(minutes/60);
var days = Math.floor(hours/24);

hours = hours-(days*24);
minutes = minutes-(days*24*60)-(hours*60);
seconds = seconds-(days*24*60*60)-(hours*60*60)-(minutes*60);

#3


16  

I call it the "snowman-carl ☃ method" and I think it's a little more flexible when you need additional timespans like weeks, moths, years, centuries... and don't want too much repetitive code:

我把它称为“雪人卡尔☃方法”,我认为当你需要额外的时间跨度,如周,飞蛾,年,几个世纪时,它会更灵活一点......并且不需要太多的重复代码:

var d = Math.abs(date_future - date_now) / 1000;                           // delta
var r = {};                                                                // result
var s = {                                                                  // structure
    year: 31536000,
    month: 2592000,
    week: 604800, // uncomment row to ignore
    day: 86400,   // feel free to add your own row
    hour: 3600,
    minute: 60,
    second: 1
};

Object.keys(s).forEach(function(key){
    r[key] = Math.floor(d / s[key]);
    d -= r[key] * s[key];
});

// for example: {year:0,month:0,week:1,day:2,hour:34,minute:56,second:7}
console.log(r);

Have a FIDDLE

有一个FIDDLE

Inspired by Alnitak's answer.

灵感来自Alnitak的回答。

#4


7  

Please note that calculating only based on differences will not cover all cases: leap years and switching of "daylight savings time".

请注意,仅根据差异进行计算不会涵盖所有情况:闰年和“夏令时”的切换。

Javascript has poor built-in library for working with dates. I suggest you use a third party javascript library, e.g. MomentJS; you can see here the function you were looking for.

Javascript用于处理日期的内置库很差。我建议你使用第三方javascript库,例如MomentJS;你可以在这里看到你正在寻找的功能。

#5


3  

The best library that I know of for duration breakdown is countdown.js. It handles all the hard cases such as leap years and daylight savings as csg mentioned, and even allows you to specify fuzzy concepts such as months and weeks. Here's the code for your case:

我知道持续时间细分的最好的库是countdown.js。它处理所有难以处理的情况,如闰年和夏令时,如csg所提到的,甚至允许您指定模糊概念,如月和周。以下是您案例的代码:

//assuming these are in *seconds* (in case of MS don't multiply by 1000 below)
var date_now = 1218374; 
var date_future = 29384744;

diff = countdown(date_now * 1000, date_future * 1000, 
            countdown.DAYS | countdown.HOURS | countdown.MINUTES | countdown.SECONDS);
alert("days: " + diff.days + " hours: " + diff.hours + 
      " minutes: " + diff.minutes + " seconds: " + diff.seconds);

//or even better
alert(diff.toString()); 

Here's a JSFiddle, but it would probably only work in FireFox or in Chrome with web security disabled, since countdown.js is hosted with a text/plain MIME type (you're supposed to serve the file, not link to countdownjs.org).

这是一个JSFiddle,但它可能只适用于禁用Web安全的FireFox或Chrome,因为countdown.js托管文本/纯MIME类型(你应该提供文件,而不是链接到countdownjs.org) 。

#6


1  

function update(datetime = "2017-01-01 05:11:58") {
    var theevent = new Date(datetime);
    now = new Date();
    var sec_num = (theevent - now) / 1000;
    var days    = Math.floor(sec_num / (3600 * 24));
    var hours   = Math.floor((sec_num - (days * (3600 * 24)))/3600);
    var minutes = Math.floor((sec_num - (days * (3600 * 24)) - (hours * 3600)) / 60);
    var seconds = Math.floor(sec_num - (days * (3600 * 24)) - (hours * 3600) - (minutes * 60));

    if (hours   < 10) {hours   = "0"+hours;}
    if (minutes < 10) {minutes = "0"+minutes;}
    if (seconds < 10) {seconds = "0"+seconds;}

    return  days+':'+ hours+':'+minutes+':'+seconds;
}

#7


1  

Here is a code example. I used simple calculations instead of using precalculations like 1 day is 86400 seconds. So you can follow the logic with ease.

这是一个代码示例。我使用简单的计算而不是使用预先计算,如1天是86400秒。所以你可以轻松地遵循逻辑。

// Calculate time between two dates:
var date1 = new Date('1110-01-01 11:10');
var date2 = new Date();

console.log('difference in ms', date1 - date2);

// Use Math.abs() so the order of the dates can be ignored and you won't
// end up with negative numbers when date1 is before date2.
console.log('difference in ms abs', Math.abs(date1 - date2));
console.log('difference in seconds', Math.abs(date1 - date2) / 1000);

var diffInSeconds = Math.abs(date1 - date2) / 1000;
var days = Math.floor(diffInSeconds / 60 / 60 / 24);
var hours = Math.floor(diffInSeconds / 60 / 60 % 24);
var minutes = Math.floor(diffInSeconds / 60 % 60);
var seconds = Math.floor(diffInSeconds % 60);
var milliseconds = Math.round((diffInSeconds - Math.floor(diffInSeconds)) * 1000);

console.log('days', days);
console.log('hours', ('0' + hours).slice(-2));
console.log('minutes', ('0' + minutes).slice(-2));
console.log('seconds', ('0' + seconds).slice(-2));
console.log('milliseconds', ('00' + milliseconds).slice(-3));

#8


0  

here is an code to find difference between two dates in Days,Hours,Minutes,Seconds (assuming the future date is new year date).

这是一个代码,用于查找以天,小时,分钟,秒为单位的两个日期之间的差异(假设未来日期是新年日期)。

var one_day = 24*60*60*1000;              // total milliseconds in one day

var today = new Date();
var new_year = new Date("01/01/2017");    // future date

var today_time = today.getTime();         // time in miliiseconds
var new_year_time = new_year.getTime();                         

var time_diff = Math.abs(new_year_time - today_time);  //time diff in ms  
var days = Math.floor(time_diff / one_day);            // no of days

var remaining_time = time_diff - (days*one_day);      // remaining ms  

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

var minutes = Math.floor(remaining_time/(60*1000));        
remaining_time = remaining_time - (minutes * 60 * 1000);   

var seconds = Math.ceil(remaining_time / 1000);   

#1


108  

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

只需计算出以秒为单位的差异(不要忘记JS时间戳实际上以毫秒为单位)并分解该值:

// 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.

EDIT代码调整,因为我刚刚意识到原始代码返回总小时数等,而不是整天计算后剩余的小时数。

#2


23  

Here's in javascript: (For example, the future date is New Year's Day)

这里是javascript :(例如,未来的日期是新年)

DEMO (updates every second)

演示(每秒更新)

var dateFuture = new Date(new Date().getFullYear() +1, 0, 1);
var dateNow = new Date();

var seconds = Math.floor((dateFuture - (dateNow))/1000);
var minutes = Math.floor(seconds/60);
var hours = Math.floor(minutes/60);
var days = Math.floor(hours/24);

hours = hours-(days*24);
minutes = minutes-(days*24*60)-(hours*60);
seconds = seconds-(days*24*60*60)-(hours*60*60)-(minutes*60);

#3


16  

I call it the "snowman-carl ☃ method" and I think it's a little more flexible when you need additional timespans like weeks, moths, years, centuries... and don't want too much repetitive code:

我把它称为“雪人卡尔☃方法”,我认为当你需要额外的时间跨度,如周,飞蛾,年,几个世纪时,它会更灵活一点......并且不需要太多的重复代码:

var d = Math.abs(date_future - date_now) / 1000;                           // delta
var r = {};                                                                // result
var s = {                                                                  // structure
    year: 31536000,
    month: 2592000,
    week: 604800, // uncomment row to ignore
    day: 86400,   // feel free to add your own row
    hour: 3600,
    minute: 60,
    second: 1
};

Object.keys(s).forEach(function(key){
    r[key] = Math.floor(d / s[key]);
    d -= r[key] * s[key];
});

// for example: {year:0,month:0,week:1,day:2,hour:34,minute:56,second:7}
console.log(r);

Have a FIDDLE

有一个FIDDLE

Inspired by Alnitak's answer.

灵感来自Alnitak的回答。

#4


7  

Please note that calculating only based on differences will not cover all cases: leap years and switching of "daylight savings time".

请注意,仅根据差异进行计算不会涵盖所有情况:闰年和“夏令时”的切换。

Javascript has poor built-in library for working with dates. I suggest you use a third party javascript library, e.g. MomentJS; you can see here the function you were looking for.

Javascript用于处理日期的内置库很差。我建议你使用第三方javascript库,例如MomentJS;你可以在这里看到你正在寻找的功能。

#5


3  

The best library that I know of for duration breakdown is countdown.js. It handles all the hard cases such as leap years and daylight savings as csg mentioned, and even allows you to specify fuzzy concepts such as months and weeks. Here's the code for your case:

我知道持续时间细分的最好的库是countdown.js。它处理所有难以处理的情况,如闰年和夏令时,如csg所提到的,甚至允许您指定模糊概念,如月和周。以下是您案例的代码:

//assuming these are in *seconds* (in case of MS don't multiply by 1000 below)
var date_now = 1218374; 
var date_future = 29384744;

diff = countdown(date_now * 1000, date_future * 1000, 
            countdown.DAYS | countdown.HOURS | countdown.MINUTES | countdown.SECONDS);
alert("days: " + diff.days + " hours: " + diff.hours + 
      " minutes: " + diff.minutes + " seconds: " + diff.seconds);

//or even better
alert(diff.toString()); 

Here's a JSFiddle, but it would probably only work in FireFox or in Chrome with web security disabled, since countdown.js is hosted with a text/plain MIME type (you're supposed to serve the file, not link to countdownjs.org).

这是一个JSFiddle,但它可能只适用于禁用Web安全的FireFox或Chrome,因为countdown.js托管文本/纯MIME类型(你应该提供文件,而不是链接到countdownjs.org) 。

#6


1  

function update(datetime = "2017-01-01 05:11:58") {
    var theevent = new Date(datetime);
    now = new Date();
    var sec_num = (theevent - now) / 1000;
    var days    = Math.floor(sec_num / (3600 * 24));
    var hours   = Math.floor((sec_num - (days * (3600 * 24)))/3600);
    var minutes = Math.floor((sec_num - (days * (3600 * 24)) - (hours * 3600)) / 60);
    var seconds = Math.floor(sec_num - (days * (3600 * 24)) - (hours * 3600) - (minutes * 60));

    if (hours   < 10) {hours   = "0"+hours;}
    if (minutes < 10) {minutes = "0"+minutes;}
    if (seconds < 10) {seconds = "0"+seconds;}

    return  days+':'+ hours+':'+minutes+':'+seconds;
}

#7


1  

Here is a code example. I used simple calculations instead of using precalculations like 1 day is 86400 seconds. So you can follow the logic with ease.

这是一个代码示例。我使用简单的计算而不是使用预先计算,如1天是86400秒。所以你可以轻松地遵循逻辑。

// Calculate time between two dates:
var date1 = new Date('1110-01-01 11:10');
var date2 = new Date();

console.log('difference in ms', date1 - date2);

// Use Math.abs() so the order of the dates can be ignored and you won't
// end up with negative numbers when date1 is before date2.
console.log('difference in ms abs', Math.abs(date1 - date2));
console.log('difference in seconds', Math.abs(date1 - date2) / 1000);

var diffInSeconds = Math.abs(date1 - date2) / 1000;
var days = Math.floor(diffInSeconds / 60 / 60 / 24);
var hours = Math.floor(diffInSeconds / 60 / 60 % 24);
var minutes = Math.floor(diffInSeconds / 60 % 60);
var seconds = Math.floor(diffInSeconds % 60);
var milliseconds = Math.round((diffInSeconds - Math.floor(diffInSeconds)) * 1000);

console.log('days', days);
console.log('hours', ('0' + hours).slice(-2));
console.log('minutes', ('0' + minutes).slice(-2));
console.log('seconds', ('0' + seconds).slice(-2));
console.log('milliseconds', ('00' + milliseconds).slice(-3));

#8


0  

here is an code to find difference between two dates in Days,Hours,Minutes,Seconds (assuming the future date is new year date).

这是一个代码,用于查找以天,小时,分钟,秒为单位的两个日期之间的差异(假设未来日期是新年日期)。

var one_day = 24*60*60*1000;              // total milliseconds in one day

var today = new Date();
var new_year = new Date("01/01/2017");    // future date

var today_time = today.getTime();         // time in miliiseconds
var new_year_time = new_year.getTime();                         

var time_diff = Math.abs(new_year_time - today_time);  //time diff in ms  
var days = Math.floor(time_diff / one_day);            // no of days

var remaining_time = time_diff - (days*one_day);      // remaining ms  

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

var minutes = Math.floor(remaining_time/(60*1000));        
remaining_time = remaining_time - (minutes * 60 * 1000);   

var seconds = Math.ceil(remaining_time / 1000);