简体   繁体   中英

change days and hours by how time flies

I am getting the elapsed time in minutes, hours and days, between two dates, a past date and the current one, I already get this data, but I want this data to change as the minutes, days and hours increase. For example, when I get to 60 minutes, the time changes to 1 hour and the minutes go to 0, when 24 hours go by, these hours change to a day and the hours go back to 0, and so on, the data I get keeps increasing, how can I do this?

const calculateDate = () => {
    const date = new Date('Sun Sep 01 2022 01:32:06 GMT-0500');
    const currentDate = new Date();


    const minutes= Math.floor((currentDate.getTime() - date.getTime()) / 1000 / 60);
    const hours= Math.floor((currentDate.getTime() - date.getTime()) / 1000 / (3600));
    const days= Math.floor((currentDate.getTime() - date.getTime()) / (1000*60*60*24));
}

With this, get the minutes, hours and days, but how would you update so that when you reach 60 minutes it goes to one hour and 24 hours to one day?

The JavaScript Date object has built in functions for what you want to do.

var now = new Date()
var h = now.getHours()
var m = now.getMinutes()
var s = now.getSeconds()

The new Date created in above example is set to the time it was created.

You can get the current time using the Date object itself:

var current = Date()

With your method you always see the full duration just in a different unit.

You have to use the modulo operator to get only the "missing part" (the remainder of the division) to the next unit:

const date = new Date('Sun Sep 01 2022 01:32:06 GMT-0500');
const currentDate = new Date();

const dateDiff = (currentDate.getTime() - date.getTime()) / 1000;

const seconds = Math.floor(dateDiff) % 60;
const minutes = Math.floor(dateDiff / 60) % 60;
const hours   = Math.floor(dateDiff / (60 * 60)) % 24;
const days    = Math.floor(dateDiff / (60 * 60 * 24));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM