Calculate the Date difference in javascript with timer update - javascript

If you have two dates lets say dt1 and dt2.
How will you calculate the difference between them.
Here is the working example for your help:
var dt1;
var dt2;
$(document).ready(function () {
dt1 = new Date();
dt2 = new Date();
setInterval(function () {
dt2.setSeconds(dt2.getSeconds() + 1);
var diff = GetDateDiff(dt1, dt2);
$("#dtDIV").html(diff);
}, 1000);
});
function GetDateDiff(a, b) {
var msInDay = 1000 * 60 * 60 * 24;
var d1 = a.getTime();
var d2 = b.getTime();
var mlseconds = d2 - d1;
mlseconds = mlseconds / 1000;
var seconds = Math.floor(mlseconds % 60);
mlseconds = mlseconds / 60;
var minutes = Math.floor(mlseconds % 60);
mlseconds = mlseconds / 60;
var hours = Math.floor(mlseconds % 24);
var days = Math.floor(mlseconds / 24);
return days + ' days, ' + hours + ' hours, ' + minutes + ' minutes, and ' + seconds + ' seconds';
}
Full working example: http://goo.gl/5NE45o
Happy Coding !!!
Ambuj

Related

Time calculation with milliseconds in JS

I want to find difference between two time with milliseconds value in Javascript.
As you can see below snapshot, where I calculated two time values in Excel.
My expectation exactly same calculated value with JS code.
I tried some code snippet but I got slightly difference in seconds.
var d1 = '2020-12-15 01:00:23.788';
var d2 = '2020-12-15 01:00:55.482';
var date1 = new Date(d1);
var date2 = new Date(d2);
//date2 += 500;
//date2 = new Date(date2);
//date2.setMilliseconds(5);
var date1_ms = date1.getTime();
var date2_ms = date2.getTime();
// Calculate the difference in milliseconds
var difference_ms = date2_ms - date1_ms;
//take out milliseconds
difference_ms = difference_ms / 1000;
var seconds = Math.floor(difference_ms % 60);
difference_ms = difference_ms / 60;
var minutes = Math.floor(difference_ms % 60);
difference_ms = difference_ms / 60;
var hours = Math.floor(difference_ms % 24);
var demo = hours + ' hours, ' + minutes + ' minutes, and ' + seconds + ' seconds.' + difference_ms;
document.getElementById("demo").innerHTML = demo;
<h2>JavaScript new Date()</h2>
<p>new Date() creates a new date object with the current date and time:</p>
<p id="demo"></p>
OUTPUT:
new Date() creates a new date object with the current date and time:
0 hours, 0 minutes, and 31 seconds.0.008803888888888889
JS does the same when correctly implemented
I tried with more interesting times
// Excel: 02:10:55,482 - 01:09:23,788 = 01:01:31,694
const fmtTime = date => {
const hours = `0${date.getHours() - 1}`.slice(-2);
const minutes = `0${date.getMinutes()}`.slice(-2);
const seconds = `0${date.getSeconds()}`.slice(-2);
const ms = `00${date.getMilliseconds()}`.slice(-3);
return `${hours}:${minutes}:${seconds}.${ms}`
}
const from = "01:09:23,788"
const to = "02:10:55.482"
const re = /(\d{2}):(\d{2}):(\d{2}).(\d{3})/;
const [m1, fromhh, frommm, fromss, fromms] = from.match(re);
const [m2, tohh, tomm, toss, tomms] = to.match(re);
// method one
let d = new Date()
d.setHours(fromhh, frommm, fromss, fromms)
const fromTime = d.getTime()
d.setHours(tohh, tomm, toss, tomms)
const toTime = d.getTime()
const diffInMS1 = toTime - fromTime
console.log(diffInMS1)
d = new Date(diffInMS1);
console.log(fmtTime(d))
// Method 2 - Note I need to cast to int where I only add (+fromms)
let fromMS = (fromhh * 60 * 60 * 1000) + (frommm * 60 * 1000) + (fromss * 1000) + +fromms;
let toMS = (tohh * 60 * 60 * 1000) + (tomm * 60 * 1000) + (toss * 1000) + +tomms;
const diffInMS2 = toMS - fromMS;
console.log(diffInMS2)
d = new Date(diffInMS2);
console.log(fmtTime(d))
function splitInNumberArray(str) {
return str
.replace(/(:|\.)/g, " ")
.split(" ")
.map((x) => parseInt(x));
}
function convertToMilliseconds(timeArray) {
return (
timeArray[0] * 60 * 60 * 1000 +
timeArray[1] * 60 * 1000 +
timeArray[2] * 1000 +
timeArray[3]
);
}
function msToTime(duration) {
var milliseconds = parseInt((duration % 1000) / 100),
seconds = Math.floor((duration / 1000) % 60),
minutes = Math.floor((duration / (1000 * 60)) % 60),
hours = Math.floor((duration / (1000 * 60 * 60)) % 24);
hours = hours < 10 ? "0" + hours : hours;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
return hours + ":" + minutes + ":" + seconds + "." + milliseconds;
}
// This function is taken from https://stackoverflow.com/questions/19700283/how-to-convert-time-milliseconds-to-hours-min-sec-format-in-javascript
function parseDuration(duration) {
let remain = duration;
let hours = Math.floor(remain / (1000 * 60 * 60));
remain = remain % (1000 * 60 * 60);
let minutes = Math.floor(remain / (1000 * 60));
remain = remain % (1000 * 60);
let seconds = Math.floor(remain / 1000);
remain = remain % 1000;
let milliseconds = remain;
return {
hours,
minutes,
seconds,
milliseconds,
};
}
function minTwoDigits(n) {
return (n < 10 ? "0" : "") + n;
}
//***************************************
const time1 = "01:00:55.482";
const time2 = "01:00:23.788";
const numberArray1 = splitInNumberArray(time1);
const numberArray2 = splitInNumberArray(time2);
const msTime1 = convertToMilliseconds(numberArray1);
const msTime2 = convertToMilliseconds(numberArray2);
const diff = msTime1 - msTime2;
const { hours, minutes, seconds, milliseconds } = parseDuration(diff);
console.log(
`${time1} - ${time2} = ${minTwoDigits(hours)}:${minTwoDigits(
minutes
)}:${minTwoDigits(seconds)}.${milliseconds}`
);

Javascript code do not count date properly

I am using this code in order to countdown a date:
function countdown()
{
var now = new Date();
var end = new Date('Mars 13, 2016 13:12:12'),
$.each(times, function( key, value ) {
var left = end - now;
var days = Math.floor( left / (1000 * 60 * 60 * 24) );
var hours = Math.floor( (left % (1000 * 60 * 60 * 24) ) / (1000 * 60 * 60) );
var minutes = Math.floor( (left % (1000 * 60 * 60)) / (1000 * 60) );
var seconds = Math.floor( (left % (1000 * 60)) / 1000 );
displayTime = '';
if (days > 0) {
displayTime = days+' days';
}
displayTime = displayTime + ' ' +hours+' Hours ' + minutes+' Minutes ' + seconds+'s';
$('#cont'+value.id).text(displayTime)
});
}
But it doesn't counts it properly since it is not considering if month have 31 days, 28/29 days ...
And the second thing is that when it reaches the expiring date, It does not stops and continues to count down below zero.
What have i done wrong, and how to fix it please ?
The way that I do countdowns is to create a countdown initiation script called countdown.js, and then include this script in your main page with the script tag's src="countdown.js"
Here is the code for countdown.js
CountDownTimer('12/25/2016 12:0 AM', 'countdown');
//CountDownTimer('02/20/2012 10:1 AM', 'newcountdown');
function CountDownTimer(dt, id)
{
var end = new Date(dt);
var _second = 1000;
var _minute = _second * 60;
var _hour = _minute * 60;
var _day = _hour * 24;
var timer;
function showRemaining() {
var now = new Date();
var distance = end - now;
if (distance < 0) {
clearInterval(timer);
document.getElementById(id).innerHTML = 'Merry Christmas!';
return;
}
var days = Math.floor(distance / _day);
var hours = Math.floor((distance % _day) / _hour);
var minutes = Math.floor((distance % _hour) / _minute);
var seconds = Math.floor((distance % _minute) / _second);
if(hours < 10){
hours = "0"+hours;
}
if(minutes < 10){
minutes = "0"+minutes;
}
if(seconds < 10){
seconds = "0"+seconds;
}
document.getElementById(id).innerHTML = "<span id='daycount'>" + days + ' days</span><br/>';
document.getElementById(id).innerHTML += hours + ':';
document.getElementById(id).innerHTML += minutes + ':';
document.getElementById(id).innerHTML += seconds + '';
}
timer = setInterval(showRemaining, 1000);
}
Now on your main page
Include the countdown script with <script src="countdown.js"></script> in your <head>.
Then create a div with id="countdown".
The countdown div's id is defined by the first line of the countdown.js script, as the second function input for CountDownTimer();.
My code is set to count down to christmas, you change change this date and time easily by modifying the first line of countdown.js to suit your date needs. Make sure you use the same format as the supplied date though! mm/dd/yyyy H:m AM/PM
You should not parse strings with the Date constructor (or Date.parse, they are equivalent for parsing). Either write a small function yourself or use a library.
Also, if your code depends on a particular library, you should include a tag for that. There are many posts here on how to create a timer.
The code you've posted does not have any months so it's unclear why you're having an issue with them. Perhaps you want to count down years, moths, days, etc.? That's a much more difficult issue than just days, hours, etc. and there are questions and answers for that too.
var countDown = (function() {
var endDate;
return function(eDate) {
endDate = endDate || eDate;
var msg = '';
var now = Date.now();
var r = endDate - now;
var d, h, m, s;
if (r <= 1000) {
msg = 'Finished!';
} else {
d = r / 8.64e7 | 0;
h = r % 8.64e7 / 3.6e6 | 0;
m = r % 3.6e6 / 6e4 | 0;
s = r % 6e4 / 1000 | 0;
msg = (d? d + ' day' + (d == 1? '':'s') + ', ' : '') +
h + ' hour' + (h==1?'':'s') + ', ' +
m + ' minute' + (m==1?'':'s') + ' and ' +
s + ' second' + (s==1?'':'s');
}
document.getElementById('counter').textContent = msg;
var lag = 1010 - (Date.now() % 1000);
if (r > 0) {
setTimeout(countDown, lag);
}
}
}());
countDown(new Date(2016,11,25));
<span id="counter"></span>

JavaScript Countdown Timer to specific time everyday

I am currently developing a website with a countdown timer at the headline: http://iphone.myhandykey.com/
The current timer is just 12hrs + few mins.. What I would like is the countdown timer will show the time remaining until 11PM on the Time Zone of the current visitor. Is that possible? Thanks!
Here is the JavaScript:
function startTimer(duration, display) {
var timer = duration, hours, minutes, seconds;
setInterval(function () {
hours = parseInt(((timer / 60) / 60 ) % 60, 10);
minutes = parseInt((timer / 60)%60, 10);
seconds = parseInt(timer % 60, 10);
hours = hours < 10 ? "0" + hours : hours;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = hours + ":" + minutes + ":" + seconds;
if (--timer < 0) {
timer = duration;
}
}, 1000);
}
window.onload = function () {
var onehour = 60 * 600 * 1.231,
display = document.querySelector('#time');
startTimer(onehour, display);
};
Here is the HTML:
<span id=time></span>
EDIT: If the visitor's current time is for example 11:40pm, It should display 23hrs & 20mins left..
(function() {
var start = new Date;
start.setHours(23, 0, 0); // 11pm
function pad(num) {
return ("0" + parseInt(num)).substr(-2);
}
function tick() {
var now = new Date;
if (now > start) { // too late, go to tomorrow
start.setDate(start.getDate() + 1);
}
var remain = ((start - now) / 1000);
var hh = pad((remain / 60 / 60) % 60);
var mm = pad((remain / 60) % 60);
var ss = pad(remain % 60);
document.getElementById('time').innerHTML =
hh + ":" + mm + ":" + ss;
setTimeout(tick, 1000);
}
document.addEventListener('DOMContentLoaded', tick);
})();
Only <span id='time'></span> left!
Something like this:
$(document).ready(function () {
var mg = new Date(2016, 5, 21, 0, 0, 0, 0);
var tmr = window.setInterval(function () {
var d = new Date();
var dif = mg - d;
var s = parseInt(dif / 1000);
if (s < 0) {
document.getElementById('spCnt').innerHTML = 'Event starts';
window.clearInterval(tmr);
return;
}
var sec = s % 60;
var m = parseInt(s / 60);
var min = m % 60;
var h = parseInt(m / 60);
var hour = h % 24;
d = parseInt(h / 24);
document.getElementById('spCnt').innerHTML = d + ' days ' + hour + ' hours ' + min + ' min and ' + sec + ' sec remaining';
}, 1000);
});

Reset and restart javascript countdown (loop)

I have this pure JavaScript countdown based on date object all working fine except that I wanted the countdown to keep running.
JSFiddle sample
//the countdown part
var d = new Date();
var theDate = d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate();
var newTime = new Date(Date.parse(d) + secs * 1000);
//var end = new Date('02/08/2016 10:00:00');
var end = newTime;
var _second = 1000;
var _minute = _second * 60;
var _hour = _minute * 60;
var _day = _hour * 24;
var timer;
if (timer) clearInterval(timer);
function showRemaining() {
var now = new Date();
var distance = end - now;
if (distance < 0) {
clearInterval(timer);
document.getElementById('countdown').innerHTML = 'this is the callback from here should reset and starts again';
return;
}
var days = Math.floor(distance / _day);
var hours = Math.floor((distance % _day) / _hour);
var minutes = Math.floor((distance % _hour) / _minute);
var seconds = Math.floor((distance % _minute) / _second);
document.getElementById('countdown').innerHTML = days + 'days ';
document.getElementById('countdown').innerHTML += hours + 'hrs ';
document.getElementById('countdown').innerHTML += minutes + 'mins ';
document.getElementById('countdown').innerHTML += seconds + 'secs';
}
timer = setInterval(showRemaining, 1000);
In the if (distance < 0) branch, you simply need to remove clearInterval and reset the end variable.
Something like this:
if (distance < 0) {
d = new Date();
theDate = d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate();
newTime = new Date(Date.parse(d) + secs * 1000);
end = newTime;
return;
}

JavaScript date difference correction

I have a function that will calculate time between two date / time but I am having a small issue with the return.
Here is the way I collect the information.
Start Date
Start Time
Ending Date
Ending Time
Hours
And here is the function that calculates the dates and times:
function calculate (form) {
var d1 = document.getElementById("date1").value;
var d2 = document.getElementById("date2").value;
var t1 = document.getElementById("time1").value;
var t2 = document.getElementById("time2").value;
var dd1 = d1 + " " + t1;
var dd2 = d2 + " " + t2;
var date1 = new Date(dd1);
var date2 = new Date(dd2);
var sec = date2.getTime() - date1.getTime();
if (isNaN(sec)) {
alert("Input data is incorrect!");
return;
}
if (sec < 0) {
alert("The second date ocurred earlier than the first one!");
return;
}
var second = 1000,
minute = 60 * second,
hour = 60 * minute,
day = 24 * hour;
var hours = Math.floor(sec / hour);
sec -= hours * hour;
var minutes = Math.floor(sec / minute);
sec -= minutes * minute;
var seconds = Math.floor(sec / second);
var min = Math.floor((minutes * 100) / 60);
document.getElementById("result").value = hours + '.' + min;
}
If I put in todays date for both date fields and then 14:30 in the first time field and 15:35 in the second time field the result is shown as 1.8 and it should be 1.08
I didn't write this function but I am wondering if someone could tell me how to make that change?
Thank you.
If I understand correctly, the only issue you are having is that the minutes are not padded by zeroes. If this is the case, you can pad the value of min with zeroes using this little trick:
("00" + min).slice(-2)
I can't see why 15:35 - 14:30 = 1.08 is useful?
Try this instead:
function timediff( date1, date2 ) {
//Get 1 day in milliseconds
var one_day=1000*60*60*24;
// Convert both dates to milliseconds
var date1_ms = date1.getTime();
var date2_ms = date2.getTime();
// Calculate the difference in milliseconds
var difference_ms = date2_ms - date1_ms;
//take out milliseconds
difference_ms = difference_ms/1000;
var seconds = Math.floor(difference_ms % 60);
difference_ms = difference_ms/60;
var minutes = Math.floor(difference_ms % 60);
difference_ms = difference_ms/60;
var hours = Math.floor(difference_ms % 24);
var days = Math.floor(difference_ms/24);
return [days,hours,minutes,seconds];
}
function calculate (form) {
var d1 = document.getElementById("date1").value;
var d2 = document.getElementById("date2").value;
var t1 = document.getElementById("time1").value;
var t2 = document.getElementById("time2").value;
var dd1 = d1 + " " + t1;
var dd2 = d2 + " " + t2;
var date1 = new Date(dd1);
var date2 = new Date(dd2);
var diff = timediff(date1, date2);
document.getElementById("result").value = diff[1] + ':' + diff[2];
}
Verify if number of minutes is less than 10 and if it is then append an additional zero in front. Follow similar approach for seconds.

Categories

Resources