I have two date time pickers in Jquery.
I need to show the difference on clicking the show button in the textbox with id result.
If
Time1 = 04/30/2014 10:27 am
Time2 = 05/01/2014 10:26 am
It should calculate its difference and show the result like X days Y Hrs Z minutes
In addition I want the date to be in dd/mm/yy. Right now it is mm/dd/yy.
Fiddle
Fiddle Demo
var time1 = $('#basic_example_1'), //cache selectors
time2 = $('#basic_example_2'),
result = $("#result");
$("#show").click(function () {
var d1 = new Date(time1.val()), //convert to date object
d2 = new Date(time2.val()), //convert to date object
msec = d2.getTime() - d1.getTime(), //get difference in milliseconds
hh = Math.floor(msec / 1000 / 60 / 60), //get hours
dd = Math.floor(hh / 24); //calculate days
msec -= hh * 1000 * 60 * 60; //remove hours from msec
hh -= dd * 24; //remove days from hours
var mm = Math.floor(msec / 1000 / 60); //get minutes
result.val(dd + ' days ' + hh + ' Hrs ' + mm + ' minutes');
});
var start = $('#basic_example_1').datepicker('getDate');
var end = $('#basic_example_2').datepicker('getDate');
var diff = new Date(end - start);
var days = Math.floor(diff/1000/60/60/24);
var hours = Math.floor((diff % ( 1000 * 60 * 60 * 24)) / 1000 / 60 / 60);
var minutes = Math.floor((diff % ( 1000 * 60 * 60)) / 1000 / 60);
$("#result").val(days+' Day(s) '+hours+' Hour(s) '+minutes+' Minute(s)');
Fiddle
Related
I would like to create a counter that reset every week, I found a code that more or less works, but when It goes to 0, it appears negative.... -1d -1h -2m -5s
<script>
// Set the date we're counting down to
var countDownDate = new Date("Jan 29, 2021 20:21:0").getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now an the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Display the result in the element with id="demo"
document.getElementById("demo").innerHTML = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";
// If the count down is finished, write some text
if (distance < 0) {
//document.getElementById("demo").innerHTML = "GAME DAY";
if(distance < - 1000 * 60 * 60* 24){ // if its past the "game day"
// reset timer to next week
countDownDate += 1000 * 60 * 60 * 24 * 7
}
}
}, 1000);
</script>
<span id="demo"></span>
Instead of hard-coding the date, you need to calculate the next date based on the current date.
Something like this, though you'd be better of moving the magic numbers (5 and 20) into variables.
let getNextGameDayTime = function() {
let now = new Date();
let dayOfTheWeek = now.getDay();
let dayOffset = 5 - dayOfTheWeek; // Friday is the 5th day of the week
if (dayOffset < 0 || (dayOffset === 0 && now.getHours() > 20)) {
dayOffset += 7;
}
let result = new Date();
result.setDate(result.getDate() + dayOffset);
result.setHours(20);
result.setMinutes(0);
result.setSeconds(0);
result.setMilliseconds(0);
return result;
}
console.log(getNextGameDayTime());
As for not displaying the message for the hour after a countdown has finished, you could use the resulting distance for this.
(function timeAgo(selector) {
console.clear();
var dt1 = new Date("2019-12-17 13:12:34");
var dt2 = new Date();
var diff = (dt2.getTime() - dt1.getTime());
var hours = Math.floor(diff / (1000 * 60 * 60));
diff -= hours * (1000 * 60 * 60);
var mins = Math.floor(diff / (1000 * 60));
diff -= mins * (1000 * 60);
document.getElementById("demo").innerHTML = mins + 'minutes ago';
setTimeout(timeAgo, 60000);
})();
<span id="demo" />
Use moment.js.
moment("20111031", "YYYYMMDD").fromNow()
// 8 years ago
moment.js is great, you can use that but in case you are looking for a pure JS solution:
(function getTimeDiff() {
let datetime = new Date("2016-04-18 01:07:23.132446").getTime();
let now = new Date().getTime();
let milisecDiff = (datetime < now) ? now - datetime : datetime - now;
let days = Math.floor(milisecDiff / 1000 / 60 / (60 * 24));
let dateDiff = new Date(milisecDiff);
console.log(`${days} Days ${dateDiff.getHours()} Hours ${dateDiff.getMinutes()} Minutes ${dateDiff.getSeconds()} Seconds`);
})();
You can further format the output to serve your use cases.
Trying to convert our existing countdown timer which counts from 7 days. Need countdown to go display start date to end date in DD HH MM.
var count = {time: new Date('Nov 12, 2019 10:00:00').getTime() };
var timeLeft = count.time - Date.now();
// displays countdown of DD HH MM correctly.
var count = { time: 7000 * 60 * 60 * 24};
function setTime() {
// var timeLeft = count.time;
var days = Math.floor(timeLeft / (1000 * 60 * 60 * 24));
timeLeft -= days * 1000;
var hours = Math.floor((timeLeft % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
timeLeft -= hours * 60 * 60;
var minutes = Math.floor((timeLeft % (1000 * 60 * 60)) / (1000 * 60));
timeLeft -= minutes * 60;
days = ("0" + days).slice(-2);
hours = ("0" + hours).slice(-2);
minutes = ("0" + minutes).slice(-2);
document.getElementById("cDay").innerHTML = days;
document.getElementById("cHour").innerHTML = hours;
document.getElementById("cMin").innerHTML = minutes;
}
Count starts correctly, but then goes into chaos, including negatives.
Show countdown timer based on specific start date+time and end date+time.
To clarify, my question is how do I make this .js calculate the countdown from an actual date+time (with the option to only display a span of time... ie: event is Nov 24-31).
We've tried to replace the "var count = { time: 7000 * 60 * 60 * 24};" to "var count = {time: new Date('Nov 24, 2019 10:00:00').getTime() };" but this blows up the countdown. I need an accurate display of Day : Hour : Minute.
I have used a countdown to get the difference between two times. When I use the special time the timer stops despite time gets the difference when refreshing the browser I find it already counts but it doesn't show counting seconds.
<p id="demo"></p>
<script>
// given the city's UTC offset
function calcTime(city, offset) {
// create Date object for current location
d = new Date();
// convert to msec
// add local time zone offset
// get UTC time in msec
utc = d.getTime() + (d.getTimezoneOffset() * 60000);
// create new Date object for different city
// using supplied offset
nd = new Date(utc + (3600000*offset));
// return time as a string
return nd;
}
var xx = calcTime('country1', '+3');
var x1 = calcTime('country2', '-1');
// Set the date we're counting down to
var countDownDate = new Date(xx).getTime();
var now = new Date(x1).getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time //1527885631789
//var now2 = new Date().getTime(); //1527871237519
// Find the distance between now an the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Output the result in an element with id="demo"
document.getElementById("demo").innerHTML = hours + "h "
+ minutes + "m " + seconds + "s ";
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
</script>
When I use var now = new Date().getTime(); the countdown works. What is the problem in my code ?
Although I'm still not clear on what you want, I believe the following code behaves how you want. The trick is that you need to update now at every interval.
// given the city's UTC offset
function calcTime(city, offset) { .. unchanged ..}
var xx = calcTime('country1', '+3');
// Set the date we're counting down to
var countDownDate = new Date(xx).getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// calculate the current time
var now = new Date(calcTime('country2', '-1')).getTime();
// Get todays date and time //1527885631789
//var now2 = new Date().getTime(); //1527871237519
// Find the distance between now an the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Output the result in an element with id="demo"
console.log(hours + "h " + minutes + "m " + seconds + "s ");
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
console.log("EXPIRED");
}
}, 1000);
This code for a countdown timer is taken from W3Schools:
// Set the date we're counting down to
var d = new Date();
var n = d.getTimezoneOffset() * 60000;
var countDownDate = new Date("May 2, 2018 15:54:25").getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now an the count down date
var distance = countDownDate - now - n;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Output the result in an element with id="demo"
document.getElementById("demo").innerHTML = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
There was a big issue with it: any date I enter would not work for different timezones, as if it was +1 hour UTC it would expire, and it would be an hour long if it was -1.
So I added the d.getTimezoneOffset() * 60000; to get the milliseconds difference, and then took it off, so if there is any difference it should calculate it.
Will it always work if I put an UTC date in the future, or is there a possible difference I don't know about (for example a special country or daylight savings that could mess it up)?