JavaScript Return Number of Days,Hours,Minutes,Seconds Between Two Dates

Javascript return number of days,hours,minutes,seconds between two dates

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.

Getting the difference between 2 dates in Javascript in hours, minutes, seconds with UTC

In your code you have:

var date1 = new Date().getTime();

There's no need to use getTime in this case. But it is helpful to use meaningful variable names:

var now = new Date();

Then there's:

var date2 = new Date("05/29/2017").getTime();

Don't use the Date constructor (or Date.parse) to parse strings as it's mostly implementation dependent and inconsistent. If you have a specific date, pass values directly to the constructor.

Regarding "use UTC", that's a bit confusing as ECMAScript Date objects are UTC. They use the host timezone offset to calculate an internal UTC time value, and also to display "local" date and time values. The only way I can interpret "use UTC" is to use Date.UTC to create a date instance, e.g.:

var endDate = new Date(Date.UTC(2017,4,29)); // 2017-05-29T00:00:00Z

Now you can get the difference between then an now using:

var diff = endDate - now; 

When trying to get the hours, minutes and seconds you have:

var seconds = diff / 1000;
var minutes = (diff / 1000) / 60;
var hours = minutes / 60;

That converts the entire difference to each of hours, minutes and seconds so the total time is about 3 times what it should be. What you need is just the components, so:

var hours = Math.floor(diff / 3.6e5);
var minutes = Math.floor(diff % 3.6e5) / 6e4);
var seconds = Math.floor(diff % 6e4) / 1000;

Putting it all together in one function:

function timeLeft() {    var now = new Date();    var endDate = new Date(Date.UTC(2017,4,29)); // 2017-05-29T00:00:00Z    var diff = endDate - now; 
var hours = Math.floor(diff / 3.6e6); var minutes = Math.floor((diff % 3.6e6) / 6e4); var seconds = Math.floor((diff % 6e4) / 1000); console.log('Time remaining to ' + endDate.toISOString() + ' or\n' + endDate.toString() + ' local is\n' + hours + ' hours, ' + minutes + ' minutes and ' + seconds + ' seconds');}
timeLeft()

JavaScript - Get minutes between two dates

You may checkout this code:

var today = new Date();
var Christmas = new Date(today.getFullYear() + "-12-25");
var diffMs = (Christmas - today); // milliseconds between now & Christmas
var diffDays = Math.floor(diffMs / 86400000); // days
var diffHrs = Math.floor((diffMs % 86400000) / 3600000); // hours
var diffMins = Math.round(((diffMs % 86400000) % 3600000) / 60000); // minutes
console.log(diffDays + " days, " + diffHrs + " hours, " + diffMins + " minutes until Christmas =)");

How to calculate number of days between two dates?

Here is a quick and dirty implementation of datediff, as a proof of concept to solve the problem as presented in the question. It relies on the fact that you can get the elapsed milliseconds between two dates by subtracting them, which coerces them into their primitive number value (milliseconds since the start of 1970).

/**
* Take the difference between the dates and divide by milliseconds per day.
* Round to nearest whole number to deal with DST.
*/
function datediff(first, second) {
return Math.round((second - first) / (1000 * 60 * 60 * 24));
}

/**
* new Date("dateString") is browser-dependent and discouraged, so we'll write
* a simple parse function for U.S. date format (which does no error checking)
*/
function parseDate(str) {
var mdy = str.split('/');
return new Date(mdy[2], mdy[0] - 1, mdy[1]);
}

alert(datediff(parseDate(first.value), parseDate(second.value)));
<input id="first" value="1/1/2000"/>
<input id="second" value="1/1/2001"/>

How to calculate the time left in days, hours, minutes, and seconds left to reach certain day?

Set a Valid End Date
First, you’ll need to set a valid end date. This should be a string in any of the formats understood by JavaScript’s Date.parse() method. For example:

const deadline = '2015-12-31';

The short format:

const deadline = '31/12/2015';

Or, the long format:

const deadline = 'December 31 2015';

Each of these formats allows you to specify an exact time and a time zone (or an offset from UTC in the case of ISO dates). For example:

const deadline = 'December 31 2015 23:59:59 GMT+0200';

Calculate the Time Remaining
The next step is to calculate the time remaining. We need to write a function that takes a string representing a given end time (as outlined above). We then calculate the difference between that time and the current time. Here’s what that looks like:

 function getTimeRemaining(endtime){
const total = Date.parse(endtime) - Date.parse(new Date());
const seconds = Math.floor( (total/1000) % 60 );
const minutes = Math.floor( (total/1000/60) % 60 );
const hours = Math.floor( (total/(1000*60*60)) % 24 );
const days = Math.floor( total/(1000*60*60*24) );

return {
total,
days,
hours,
minutes,
seconds
};
}

First, we’re creating a variable total, to hold the remaining time until the deadline. The Date.parse() function converts a time string into a value in milliseconds. This allows us to subtract two times from each other and get the amount of time in between.

const total = Date.parse(endtime) - Date.parse(new Date());

Convert the Time to a Usable Format
Now we want to convert the milliseconds to days, hours, minutes, and seconds. Let’s use seconds as an example:

const seconds = Math.floor( (t/1000) % 60 );

Let’s break down what’s going on here.

  1. Divide milliseconds by 1000 to convert to seconds: (t/1000)
  2. Divide the total seconds by 60 and grab the remainder. You don’t want all of the seconds, just those remaining after the minutes have been counted: (t/1000) % 60
  3. Round this down to the nearest whole number. This is because you want complete seconds, not fractions of seconds: Math.floor( (t/1000) % 60 )

Repeat this logic to convert the milliseconds to minutes, hours, and days.

Output the Clock Data as a Reusable Object

With the days, hours, minutes, and seconds prepared, we’re now ready to return the data as a reusable object:

return {
total,
days,
hours,
minutes,
seconds
};

This object allows you to call your function and get any of the calculated values. Here’s an example of how you’d get the remaining minutes:

getTimeRemaining(deadline).minutes

Convenient, right?

..
Display the Clock and Stop It When It Reaches Zero

Now that we have a function that spits out the days, hours, minutes, and seconds remaining, we can build our clock. First we’ll create the following HTML element to hold our clock:

<div id="clockdiv"></div>

Then we’ll write a function that outputs the clock data inside our new div:

function initializeClock(id, endtime) {
const clock = document.getElementById(id);
const timeinterval = setInterval(() => {
const t = getTimeRemaining(endtime);
clock.innerHTML = 'days: ' + t.days + '<br>' +
'hours: '+ t.hours + '<br>' +
'minutes: ' + t.minutes + '<br>' +
'seconds: ' + t.seconds;
if (t.total <= 0) {
clearInterval(timeinterval);
}
},1000);
}

This function takes two parameters. These are the id of the element that contains our clock, and the countdown’s end time. Inside the function, we’ll declare a clock variable and use it to store a reference to our clock container div. This means we don’t have to keep querying the DOM.
Next, we’ll use setInterval to execute an anonymous function every second. This function will do the following:

Calculate the remaining time.
Output the remaining time to our div.
If the remaining time gets to zero, stop the clock.

At this point, the only remaining step is to run the clock like so:

initializeClock('clockdiv', deadline);

Congratulations! You now have a basic clock in just 18 lines of JavaScript.

Prepare Your Clock for Display
Before styling the clock, we’ll need to refine things a little.

Remove the initial delay so your clock shows up immediately.
Make the clock script more efficient so it doesn’t continuously rebuild the whole clock.
Add leading zeros as desired.

Remove the Initial Delay
In the clock, we’ve used setInterval to update the display every second. This is fine most of the time, except in the beginning when there will be a one-second delay. To remove this delay, we’ll have to update the clock once before the interval starts.

Let’s move the anonymous function that we’re passing to setInterval into its own separate function. We can name this function updateClock. Call the updateClock function once outside of setInterval, and then call it again inside setInterval. This way, the clock shows up without the delay.

In your JavaScript, replace this:

const timeinterval = setInterval(() => { ... },1000);

With this:

function updateClock(){
const t = getTimeRemaining(endtime);
clock.innerHTML = 'days: ' + t.days + '<br>' +
'hours: '+ t.hours + '<br>' +
'minutes: ' + t.minutes + '<br>' +
'seconds: ' + t.seconds;
if (t.total <= 0) {
clearInterval(timeinterval);
}
}

updateClock(); // run function once at first to avoid delay
var timeinterval = setInterval(updateClock,1000);

Avoid Continuously Rebuilding the Clock
We need to make the clock script more efficient. We’ll want to update only the numbers in the clock instead of rebuilding the entire clock every second. One way to accomplish this is to put each number inside a span tag and only update the content of those spans.

Here’s the HTML:

<div id="clockdiv">
Days: <span class="days"></span><br>
Hours: <span class="hours"></span><br>
Minutes: <span class="minutes"></span><br>
Seconds: <span class="seconds"></span>
</div>

Now let’s get a reference to those elements. Add the following code right after where the clock variable is defined

const daysSpan = clock.querySelector('.days');
const hoursSpan = clock.querySelector('.hours');
const minutesSpan = clock.querySelector('.minutes');
const secondsSpan = clock.querySelector('.seconds');

Next, we need to alter the updateClock function to update only the numbers. The new code will look like this:

function updateClock(){
const t = getTimeRemaining(endtime);

daysSpan.innerHTML = t.days;
hoursSpan.innerHTML = t.hours;
minutesSpan.innerHTML = t.minutes;
secondsSpan.innerHTML = t.seconds;

...
}

Add Leading Zeros
Now that the clock is no longer rebuilding every second, we have one more thing to do: add leading zeros. For example, instead of having the clock show 7 seconds, it would show 07 seconds. One simple way to do this is to add a string of ‘0′ to the beginning of a number and then slice off the last two digits.

For example, to add a leading zero to the “seconds” value, you’d change this:

secondsSpan.innerHTML = t.seconds;

to this:

secondsSpan.innerHTML = ('0' + t.seconds).slice(-2);

If you’d like, you can add leading zeros to the minutes and hours as well. If you’ve come this far, congratulations! Your clock is now ready for display.

Note: You may have to click “Rerun” in the CodePen for the countdown to start.

Get time difference between two dates in seconds

The Code

var startDate = new Date();
// Do your operations
var endDate = new Date();
var seconds = (endDate.getTime() - startDate.getTime()) / 1000;

Or even simpler (endDate - startDate) / 1000 as pointed out in the comments unless you're using typescript.



The explanation

You need to call the getTime() method for the Date objects, and then simply subtract them and divide by 1000 (since it's originally in milliseconds). As an extra, when you're calling the getDate() method, you're in fact getting the day of the month as an integer between 1 and 31 (not zero based) as opposed to the epoch time you'd get from calling the getTime() method, representing the number of milliseconds since January 1st 1970, 00:00



Rant

Depending on what your date related operations are, you might want to invest in integrating a library such as day.js or Luxon which make things so much easier for the developer, but that's just a matter of personal preference.

For example in Luxon we would do t1.diff(t2, "seconds") which is beautiful.



Useful docs for this answer

  • Why 1970?
  • Date object
  • Date's getTime method
  • Date's getDate method
  • Need more accuracy than just seconds?

How to get the hours difference between two date objects?

The simplest way would be to directly subtract the date objects from one another.

For example:

var hours = Math.abs(date1 - date2) / 36e5;

The subtraction returns the difference between the two dates in milliseconds. 36e5 is the scientific notation for 60*60*1000, dividing by which converts the milliseconds difference into hours.

Difference between two dates in minute, hours javascript

Try:

var diffHrs = Math.floor((hourDiff % 86400000) / 3600000);

Math.round rounded the 0.5 hour difference up to 1. You only want to get the "full" hours in your hours variable, do you remove all the minutes from the variable with the Math.floor()



Related Topics



Leave a reply



Submit