How do you create a 12hour time in JavaScript - javascript

I would like to have a timer where it does something after 12 hours. I would like to begin at 6am and end at 6pm. The time only needs to be for 12 hours. I would like to know how I can adjust the time. What I would like to do is convert my current 12-hour clock into 24 hours.
I'm looking for working examples
The code example is in this CodePen link
Timer Link
(function () {
const second = 1000,
minute = second * 60,
hour = minute * 60,
day = hour * 24;
let birthday = "Nov 25, 2020 00:00:00",
countDown = new Date(birthday).getTime(),
x = setInterval(function() {
let now = new Date().getTime(),
distance = countDown - now;
document.getElementById("days").innerText = Math.floor(distance / (day)),
document.getElementById("hours").innerText = Math.floor((distance % (day)) / (hour)),
document.getElementById("minutes").innerText = Math.floor((distance % (hour)) / (minute)),
document.getElementById("seconds").innerText = Math.floor((distance % (minute)) / second);
//do something later when date is reached
if (distance < 0) {
let headline = document.getElementById("headline"),
countdown = document.getElementById("countdown"),
content = document.getElementById("content");
headline.innerText = "It's my birthday!";
countdown.style.display = "none";
content.style.display = "block";
clearInterval(x);
}
//seconds
}, 0)
}());

I would use Luxon.js:
npm install luxon
Then, it's an easy...
const {DateTime, Duration} = require('luxon');
function countdown(zeroDate) {
const zero = DateTime.fromISO(zeroDate);
const timer = setInterval(function() {
const delta = zero
.diff(DateTime.local())
.shiftTo('days', 'hours', 'minutes', 'seconds', 'milliseconds');
const {days: d, hours: h, minutes: m, seconds: s} = delta;
if ( delta.valueOf() < 1 ) {
console.log("Happy Birthday!");
clearInterval(timer);
} else {
console.log(`${d}d ${h}h ${m}m ${s}s Remaining`);
}
}, 1000 );
}
If invoked with
const {DateTime, Duration} = require('luxon');
const start = DateTime.local().plus({seconds: 15}).toISO();
countdown(start);

This should work, it will show the time until 8:00 PM when its 8:00 AM. Here's the pen I made to test it Time Until.
var doIt = false;
var now = new Date();
var seconds;
var date1;
var eight = new Date();
eight.setHours(20, 0, 0);
var date2;
var toHHMMSS = (secs) => {
var sec_num = parseInt(secs, 10)
var hours = Math.floor(sec_num / 3600)
var minutes = Math.floor(sec_num / 60) % 60
var seconds = sec_num % 60
return [hours,minutes,seconds]
.map(v => v < 10 ? "0" + v : v)
.filter((v,i) => v !== "00" || i > 0)
.join(":")
}
function diff_seconds(dt2, dt1)
{
var diff =(dt2.getTime() - dt1.getTime()) / 1000;
return Math.abs(Math.round(diff));
}
window.setInterval(function(){
date2 = new Date();
if(date2.getHours() >= 8) {
doIt = true;
}
}, 1);
window.setInterval(function(){
date2 = new Date();
if(date2.getHours() >= 20){
doIt = false;
}
}, 1);
window.setInterval(function(){
if(doIt === true){
seconds = diff_seconds(new Date(), eight);
document.querySelector("p").textContent = "It is from 8AM to 8PM";
document.querySelector("#hours").textContent = toHHMMSS(seconds);
}
}, 1000)
<p>It is not 8 AM yet</p>
<div id="hours"></div>
Hope it works!

Related

Timer continues after 0

I made a timer for a project in school (I am still in school yes and I do not have JavaScript as a lesson that we get this semester) in JavaScript and it continues after the 0. I got some help from a teacher but I can't reach him with the pandemic and stuff.
This is the code that I wrote and what happens is that when it reaches the date that I put in it goes into -0 -0 -0 -01 and continues from there.
const countdown = () => {
let countDate = new Date('Febuary 9, 2022 00:00:00').getTime();
let now = new Date().getTime();
let gap = countDate - now;
let second = 1000;
let minute = second * 60;
let hour = minute * 60;
let day = hour * 24;
let textDay = Math.floor(gap / day);
let textHour = Math.floor((gap % day) / hour);
let textMinute = Math.floor((gap % hour) / minute);
let textSecond = Math.floor((gap % minute) / second);
document.querySelector('.day').innerText = textDay;
document.querySelector('.hour').innerText = textHour;
document.querySelector('.minute').innerText = textMinute;
document.querySelector('.second').innerText = textSecond;
};
setInterval(countdown, 1000);
setInterval returns a value which you can pass to clearInterval to stop the interval from running. Store that value in a variable, for example:
let countInterval = 0;
const countdown = () => {
//...
};
countInterval = setInterval(countdown, 1000);
Then within countdown you can check if you want to clear that interval. For example, if you want to clear it when gap <= 0 you would perform that logic:
if (gap <= 0) {
clearInterval(countInterval);
return;
}
This would stop the interval from running when that condition is eventually met.
Example:
let countInterval = 0;
const countdown = () => {
let countDate = new Date('January 11, 2022 13:35:00').getTime();
let now = new Date().getTime();
let gap = countDate - now;
if (gap <= 0) {
clearInterval(countInterval);
return;
}
let second = 1000;
let minute = second * 60;
let hour = minute * 60;
let day = hour * 24;
let textDay = Math.floor(gap / day);
let textHour = Math.floor((gap % day) / hour);
let textMinute = Math.floor((gap % hour) / minute);
let textSecond = Math.floor((gap % minute) / second);
document.querySelector('.day').innerText = textDay;
document.querySelector('.hour').innerText = textHour;
document.querySelector('.minute').innerText = textMinute;
document.querySelector('.second').innerText = textSecond;
};
countInterval = setInterval(countdown, 1000);
<div class="day"></div>
<div class="hour"></div>
<div class="minute"></div>
<div class="second"></div>

Countdown Timer Ends Meessage

A few days ago, I created countdown timer by watching a video on YouTube. The countdown timer is completely perfect but one thing is missing from it. When the timer goes to the zero it will hide from the page.
I want to show some text when timer ends. Like if timer goes to zero then timer hides and show this message "You are too late. Stay with us".
This is a .js code in which I need some modification.
const dayDisplay = document.querySelector(".days .number");
const hourDisplay = document.querySelector(".hours .number");
const minuteDisplay = document.querySelector(".minutes .number");
const secondDisplay = document.querySelector(".seconds .number");
const countdownContainer = document.querySelector(".countdown-container");
const endDate = new Date("August 04 2020 10:38:00");
let saleEnded = false;
const updateTimer = () => {
if(countdownContainer) {
let currentDate = new Date();
let difference = endDate.getTime() - currentDate.getTime();
if (difference <= 1000) {
saleEnded = true;
}
const second = 1000;
const minute = second * 60;
const hour = minute * 60;
const day = hour * 24;
let newDay = Math.floor(difference / day);
let newHour = Math.floor((difference % day) / hour);
let newMiute = Math.floor((difference % hour) / minute);
let newSecond = Math.floor((difference % minute) / second);
dayDisplay.innerText = newDay < 10 ? "0" + newDay : newDay;
hourDisplay.innerText = newHour < 10 ? "0" + newHour : newHour;
minuteDisplay.innerText = newMiute < 10 ? "0" + newMiute : newMiute;
secondDisplay.innerText = newSecond < 10 ? "0" + newSecond : newSecond;
};
};
setInterval(() => {
if (!saleEnded) {
updateTimer();
} else {
countdownContainer.style.display = "block";
}
}, 1000);
Try this?
setInterval(() => {
if (!saleEnded) {
updateTimer();
} else {
countdownContainer.style.display = "block";
countdownContainer.innetHTML="You are too late. Stay with us";
}
}, 1000);

Javascript Count Up Timer

I am trying to make a javascript timer that when initiated, starts counting up. The timer is just a visual reference from when a start button is clicked to when the end button is clicked.
I found a plugin online which works perfectly for counting down but I am trying to modify it to count up.
I hard coded a date way in the future. I am now trying to get the timer to start counting up to that date. This will be reset every time the start button is clicked.
This is the function I am working with. it works perfectly to count down but I cant figure out how to reverse it.
I thought it was something with how the differece was calculated but I believe it actually happens in the //calculate dates section.
Is there an easy way to reverse this math and have it count up instead?
Fiddle: http://jsfiddle.net/xzjoxehj/
var currentDate = function () {
// get client's current date
var date = new Date();
// turn date to utc
var utc = date.getTime() + (date.getTimezoneOffset() * 60000);
// set new Date object
var new_date = new Date(utc + (3600000*settings.offset))
return new_date;
};
function countdown () {
var target_date = new Date('12/31/2020 12:00:00'), // Count up to this date
current_date = currentDate(); // get fixed current date
// difference of dates
var difference = current_date - target_date;
// if difference is negative than it's pass the target date
if (difference > 0) {
// stop timer
clearInterval(interval);
if (callback && typeof callback === 'function') callback();
return;
}
// basic math variables
var _second = 1000,
_minute = _second * 60,
_hour = _minute * 60,
_day = _hour * 24;
// calculate dates
var days = Math.floor(difference / _day),
hours = Math.floor((difference % _day) / _hour),
minutes = Math.floor((difference % _hour) / _minute),
seconds = Math.floor((difference % _minute) / _second);
// fix dates so that it will show two digets
days = (String(days).length >= 2) ? days : '0' + days;
hours = (String(hours).length >= 2) ? hours : '0' + hours;
minutes = (String(minutes).length >= 2) ? minutes : '0' + minutes;
seconds = (String(seconds).length >= 2) ? seconds : '0' + seconds;
// set to DOM
//
};
// start
var interval = setInterval(countdown, 1000);
};
JSFiddle
var original_date = currentDate();
var target_date = new Date('12/31/2020 12:00:00'); // Count up to this date
var interval;
function resetCountdown() {
original_date = currentDate();
}
function stopCountdown() {
clearInterval(interval);
}
function countdown () {
var current_date = currentDate(); // get fixed current date
// difference of dates
var difference = current_date - original_date;
if (current_date >= target_date) {
// stop timer
clearInterval(interval);
if (callback && typeof callback === 'function') callback();
return;
}
// basic math variables
var _second = 1000,
_minute = _second * 60,
_hour = _minute * 60,
_day = _hour * 24;
// calculate dates
var days = Math.floor(difference / _day),
hours = Math.floor((difference % _day) / _hour),
minutes = Math.floor((difference % _hour) / _minute),
seconds = Math.floor((difference % _minute) / _second);
// fix dates so that it will show two digets
days = (String(days).length >= 2) ? days : '0' + days;
hours = (String(hours).length >= 2) ? hours : '0' + hours;
minutes = (String(minutes).length >= 2) ? minutes : '0' + minutes;
seconds = (String(seconds).length >= 2) ? seconds : '0' + seconds;
// set to DOM
//
};
// start
interval = setInterval(countdown, 1000);
};
This OP already has an answer but that has issue with timezone , so this answer.
DownVoters care to comment.
Try this. Fiddle
var TargetDate = new Date('2015', '08', '04', 11, 11, 30) // second parameter is month and it is from from 0-11
$('#spanTargetDate').text(TargetDate);
$('#spanStartDate').text(new Date());
var Sec = 0,
Min = 0,
Hour = 0,
Days = 0;
var counter = setInterval(function () {
var CurrentDate = new Date()
$('#spanCurrentDate').text(CurrentDate);
var Diff = TargetDate - CurrentDate;
if (Diff < 0) {
clearInterval(counter);
$('#timer').text('Target Time Expired. test in fiddle')
} else {
++Sec;
if (Sec == 59) {
++Min;
Sec = 0;
}
if (Min == 59) {
++Hour;
Min = 0;
}
if (Hour == 24) {
++Days;
Hour = 0;
}
if (Sec <= Diff) $('#timer').text(pad(Days) + " : " + pad(Hour) + " : " + pad(Min) + " : " + pad(Sec));
}
}, 1000);
function pad(number) {
if (number <= 9) {
number = ("0" + number).slice(-4);
}
return number;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Target Time - <span id="spanTargetDate"></span>
<br/>
<br/>Start Time - <span id="spanStartDate"></span>
<br/>
<br/>Current Time - <span id="spanCurrentDate"></span>
<br/>
<br/>Timer (DD:HH:MM:SS) - <span id="timer"></span>
<br/>
<br/>

Find elapsed time in javascript

I'm new to JavaScript and I'm trying to write a code which calculates the time elapsed from the time a user logged in to the current time.
Here is my code:-
function markPresent() {
window.markDate = new Date();
$(document).ready(function() {
$("div.absent").toggleClass("present");
});
updateClock();
}
function updateClock() {
var markMinutes = markDate.getMinutes();
var markSeconds = markDate.getSeconds();
var currDate = new Date();
var currMinutes = currDate.getMinutes();
var currSeconds = currDate.getSeconds();
var minutes = currMinutes - markMinutes;
if(minutes < 0) { minutes += 60; }
var seconds = currSeconds - markSeconds;
if(seconds < 0) { seconds += 60; }
if(minutes < 10) { minutes = "0" + minutes; }
if(seconds < 10) { seconds = "0" + seconds; }
var hours = 0;
if(minutes == 59 && seconds == 59) { hours++; }
if(hours < 10) { hours = "0" + hours; }
var timeElapsed = hours+':'+minutes+':'+seconds;
document.getElementById("timer").innerHTML = timeElapsed;
setTimeout(function() {updateClock()}, 1000);
}
The output is correct upto 00:59:59 but after that that O/P is:
00:59:59
01:59:59
01:59:00
01:59:01
.
.
.
.
01:59:59
01:00:00
How can I solve this and is there a more efficient way I can do this?
Thank you.
No offence, but this is massively over-enginered. Simply store the start time when the script first runs, then subtract that from the current time every time your timer fires.
There are plenty of tutorials on converting ms into a readable timestamp, so that doesn't need to be covered here.
var start = Date.now();
setInterval(function() {
document.getElementById('difference').innerHTML = Date.now() - start;
// the difference will be in ms
}, 1000);
<div id="difference"></div>
There's too much going on here.
An easier way would just be to compare markDate to the current date each time and reformat.
See Demo: http://jsfiddle.net/7e4psrzu/
function markPresent() {
window.markDate = new Date();
$(document).ready(function() {
$("div.absent").toggleClass("present");
});
updateClock();
}
function updateClock() {
var currDate = new Date();
var diff = currDate - markDate;
document.getElementById("timer").innerHTML = format(diff/1000);
setTimeout(function() {updateClock()}, 1000);
}
function format(seconds)
{
var numhours = parseInt(Math.floor(((seconds % 31536000) % 86400) / 3600),10);
var numminutes = parseInt(Math.floor((((seconds % 31536000) % 86400) % 3600) / 60),10);
var numseconds = parseInt((((seconds % 31536000) % 86400) % 3600) % 60,10);
return ((numhours<10) ? "0" + numhours : numhours)
+ ":" + ((numminutes<10) ? "0" + numminutes : numminutes)
+ ":" + ((numseconds<10) ? "0" + numseconds : numseconds);
}
markPresent();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="timer"></div>
Here is a solution I just made for my use case. I find it is quite readable. The basic premise is to simply subtract the timestamp from the current timestamp, and then divide it by the correct units:
const showElapsedTime = (timestamp) => {
if (typeof timestamp !== 'number') return 'NaN'
const SECOND = 1000
const MINUTE = 1000 * 60
const HOUR = 1000 * 60 * 60
const DAY = 1000 * 60 * 60 * 24
const MONTH = 1000 * 60 * 60 * 24 * 30
const YEAR = 1000 * 60 * 60 * 24 * 30 * 12
// const elapsed = ((new Date()).valueOf() - timestamp)
const elapsed = 1541309742360 - timestamp
if (elapsed <= MINUTE) return `${Math.round(elapsed / SECOND)}s`
if (elapsed <= HOUR) return `${Math.round(elapsed / MINUTE)}m`
if (elapsed <= DAY) return `${Math.round(elapsed / HOUR)}h`
if (elapsed <= MONTH) return `${Math.round(elapsed / DAY)}d`
if (elapsed <= YEAR) return `${Math.round(elapsed / MONTH)}mo`
return `${Math.round(elapsed / YEAR)}y`
}
const createdAt = 1541301301000
console.log(showElapsedTime(createdAt + 5000000))
console.log(showElapsedTime(createdAt))
console.log(showElapsedTime(createdAt - 500000000))
For example, if 3000 milliseconds elapsed, then 3000 is greater than SECONDS (1000) but less than MINUTES (60,000), so this function will divide 3000 by 1000 and return 3s for 3 seconds elapsed.
If you need timestamps in seconds instead of milliseconds, change all instances of 1000 to 1 (which effectively multiplies everything by 1000 to go from milliseconds to seconds (ie: because 1000ms per 1s).
Here are the scaling units in more DRY form:
const SECOND = 1000
const MINUTE = SECOND * 60
const HOUR = MINUTE * 60
const DAY = HOUR * 24
const MONTH = DAY * 30
const YEAR = MONTH * 12
We can also use console.time() and console.timeEnd() method for the same thing.
Syntax:
console.time(label);
console.timeEnd(label);
Label:
The name to give the new timer. This will identify the timer; use the same name when calling console.timeEnd() to stop the timer and get the time output to the console.
let promise = new Promise((resolve, reject) => setTimeout(resolve, 400, 'resolved'));
// Start Timer
console.time('x');
promise.then((result) => {
console.log(result);
// End Timer
console.timeEnd('x');
});
You can simply use performance.now()
Example:
start = performance.now();
elapsedTime = performance.now() - start;
var hours = 0;
if(minutes == 59 && seconds == 59)
{
hours = hours + 1;
minutes = '00';
seconds == '00';
}
I would use the getTime() method, subtract the time and then convert the result into hh:mm:ss.mmm format.
I know this is kindda old question but I'd like to apport my own solution in case anyone would like to have a JS encapsulated plugin for this. Ideally I would have: start, pause, resume, stop, reset methods. Giving the following code all of the mentioned can easily be added.
(function(w){
var timeStart,
timeEnd,
started = false,
startTimer = function (){
this.timeStart = new Date();
this.started = true;
},
getPartial = function (end) {
if (!this.started)
return 0;
else {
if (end) this.started = false;
this.timeEnd = new Date();
return (this.timeEnd - this.timeStart) / 1000;
}
},
stopTime = function () {
if (!this.started)
return 0;
else {
return this.getPartial(true);
}
},
restartTimer = function(){
this.timeStart = new Date();
};
w.Timer = {
start : startTimer,
getPartial : getPartial,
stopTime : stopTime,
restart : restartTimer
};
})(this);
Start
Partial
Stop
Restart
What I found useful is a 'port' of a C++ construct (albeit often in C++ I left show implicitly called by destructor):
var trace = console.log
function elapsed(op) {
this.op = op
this.t0 = Date.now()
}
elapsed.prototype.show = function() {
trace.apply(null, [this.op, 'msec', Date.now() - this.t0, ':'].concat(Array.from(arguments)))
}
to be used - for instance:
function debug_counters() {
const e = new elapsed('debug_counters')
const to_show = visibleProducts().length
e.show('to_show', to_show)
}

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

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?
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.
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.
Here's in javascript: (For example, the future date is New Year's Day)
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);
I call it the "snowman ☃ 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 / ES6 Version (2018) / TypeScript Version (2019)
Inspired by Alnitak's answer.
A Little bit different flavour (maybe for some ppl more readable) it works in JavaScript and as little bonus it works in TypeScript as well.
If you make sure the first date is always greater than the second than you don't need the Math.abs() Also the round brackets around the modulo operation are unnecessary. I kept them for clearance.
let diffTime = Math.abs(new Date().valueOf() - new Date('2021-11-22T18:30:00').valueOf());
let days = diffTime / (24*60*60*1000);
let hours = (days % 1) * 24;
let minutes = (hours % 1) * 60;
let secs = (minutes % 1) * 60;
[days, hours, minutes, secs] = [Math.floor(days), Math.floor(hours), Math.floor(minutes), Math.floor(secs)]
console.log(days+'d', hours+'h', minutes+'m', secs+'s');
my solution is not as clear as that, but I put it as another example
console.log(duration('2019-07-17T18:35:25.235Z', '2019-07-20T00:37:28.839Z'));
function duration(t0, t1){
let d = (new Date(t1)) - (new Date(t0));
let weekdays = Math.floor(d/1000/60/60/24/7);
let days = Math.floor(d/1000/60/60/24 - weekdays*7);
let hours = Math.floor(d/1000/60/60 - weekdays*7*24 - days*24);
let minutes = Math.floor(d/1000/60 - weekdays*7*24*60 - days*24*60 - hours*60);
let seconds = Math.floor(d/1000 - weekdays*7*24*60*60 - days*24*60*60 - hours*60*60 - minutes*60);
let milliseconds = Math.floor(d - weekdays*7*24*60*60*1000 - days*24*60*60*1000 - hours*60*60*1000 - minutes*60*1000 - seconds*1000);
let t = {};
['weekdays', 'days', 'hours', 'minutes', 'seconds', 'milliseconds'].forEach(q=>{ if (eval(q)>0) { t[q] = eval(q); } });
return t;
}
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.
Use moment.js library, for example:
var time = date_future - date_now;
var seconds = moment.duration(time).seconds();
var minutes = moment.duration(time).minutes();
var hours = moment.duration(time).hours();
var days = moment.duration(time).days();
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.
// 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));
Short and flexible with support for negative values, although by using two comma expressions :)
function timeUnitsBetween(startDate, endDate) {
let delta = Math.abs(endDate - startDate) / 1000;
const isNegative = startDate > endDate ? -1 : 1;
return [
['days', 24 * 60 * 60],
['hours', 60 * 60],
['minutes', 60],
['seconds', 1]
].reduce((acc, [key, value]) => (acc[key] = Math.floor(delta / value) * isNegative, delta -= acc[key] * isNegative * value, acc), {});
}
Example:
timeUnitsBetween(new Date("2019-02-11T02:12:03+00:00"), new Date("2019-02-11T01:00:00+00:00"));
// { days: -0, hours: -1, minutes: -12, seconds: -3 }
Inspired by RienNeVaPlu͢s solution.
Because MomentJS is quite heavy and sub-optimized, people not afraid to use a module should probably look at date-fns instead, which provides an intervalToDuration method which does what you want:
const result = intervalToDuration({
start: new Date(dateNow),
end: new Date(dateFuture),
})
And which would return an object looking like so:
{
years: 39,
months: 2,
days: 20,
hours: 7,
minutes: 5,
seconds: 0,
}
Then you can even use formatDuration to display this object as a string using the parameters you prefer
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:
//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).
For those who wants only hours and minutes use this
const oldDate = new Date("2021-04-28T13:17:31.000Z")
const newDate = new Date("2021-04-28T22:08:07.000Z")
const msToTime = (ms) => ({
hours: Math.trunc(ms/3600000),
minutes: Math.trunc((ms/3600000 - Math.trunc(ms/3600000))*60) + ((ms/3600000 - Math.trunc(ms/3600000))*60 % 1 != 0 ? 1 : 0)
})
console.log(msToTime(Math.abs(newDate-oldDate)))
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;
}
MomentJS has a function to do that:
const start = moment(j.timings.start);
const end = moment(j.timings.end);
const elapsedMinutes = end.diff(start, "minutes");
Here's my take:
timeSince(123456) => "1 day, 10 hours, 17 minutes, 36 seconds"
And the code:
function timeSince(date, longText) {
let seconds = null;
let leadingText = null;
if (date instanceof Date) {
seconds = Math.floor((new Date() - date) / 1000);
if (seconds < 0) {
leadingText = " from now";
} else {
leadingText = " ago";
}
seconds = Math.abs(seconds);
} else {
seconds = date;
leadingText = "";
}
const intervals = [
[31536000, "year" ],
[ 2592000, "month" ],
[ 86400, "day" ],
[ 3600, "hour" ],
[ 60, "minute"],
[ 1, "second"],
];
let interval = seconds;
let intervalStrings = [];
for (let i = 0; i < intervals.length; i++) {
let divResult = Math.floor(interval / intervals[i][0]);
if (divResult > 0) {
intervalStrings.push(divResult + " " + intervals[i][1] + ((divResult > 1) ? "s" : ""));
interval = interval % intervals[i][0];
if (!longText) {
break;
}
}
}
let intStr = intervalStrings.join(", ");
return intStr + leadingText;
}
Easy Way
function diff_hours(dt2, dt1)
{
var diff =(dt2.getTime() - dt1.getTime()) / 1000;
diff /= (60 * 60);
return Math.abs(Math.round(diff));
}
function diff_minutes(dt2, dt1)
{
var diff =(dt2.getTime() - dt1.getTime()) / 1000;
diff /= (60);
return Math.abs(Math.round(diff));
}
function diff_seconds(dt2, dt1)
{
var diff =(dt2.getTime() - dt1.getTime()) / 1000;
return Math.abs(Math.round(diff));
}
function diff_miliseconds(dt2, dt1)
{
var diff =(dt2.getTime() - dt1.getTime());
return Math.abs(Math.round(diff));
}
dt1 = new Date(2014,10,2);
dt2 = new Date(2014,10,3);
console.log(diff_hours(dt1, dt2));
dt1 = new Date("October 13, 2014 08:11:00");
dt2 = new Date("October 14, 2014 11:13:00");
console.log(diff_hours(dt1, dt2));
console.log(diff_minutes(dt1, dt2));
console.log(diff_seconds(dt1, dt2));
console.log(diff_miliseconds(dt1, dt2));
function calculateExamRemainingTime(exam_end_at) {
$(function(){
const calcNewYear = setInterval(function(){
const exam_ending_at = new Date(exam_end_at);
const current_time = new Date();
const totalSeconds = Math.floor((exam_ending_at - (current_time))/1000);;
const totalMinutes = Math.floor(totalSeconds/60);
const totalHours = Math.floor(totalMinutes/60);
const totalDays = Math.floor(totalHours/24);
const hours = totalHours - ( totalDays * 24 );
const minutes = totalMinutes - ( totalDays * 24 * 60 ) - ( hours * 60 );
const seconds = totalSeconds - ( totalDays * 24 * 60 * 60 ) - ( hours * 60 * 60 ) - ( minutes * 60 );
const examRemainingHoursSection = document.querySelector('#remainingHours');
const examRemainingMinutesSection = document.querySelector('#remainingMinutes');
const examRemainingSecondsSection = document.querySelector('#remainingSeconds');
examRemainingHoursSection.innerHTML = hours.toString();
examRemainingMinutesSection.innerHTML = minutes.toString();
examRemainingSecondsSection.innerHTML = seconds.toString();
},1000);
});
}
calculateExamRemainingTime('2025-06-03 20:20:20');
const arrDiff = [
{
label: 'second',
value: 1000,
},
{
label: 'minute',
value: 1000 * 60,
},
{
label: 'hour',
value: 1000 * 60 * 60,
},
{
label: 'day',
value: 1000 * 60 * 60 * 24,
},
{
label: 'year',
value: 1000 * 60 * 60 * 24 * 365,
},
];
function diff(date) {
let result = { label: '', value: '' };
const value = Date.now() - date;
for (let obj of arrDiff) {
let temp = Math.round(value / obj.value);
if (temp === 0) {
break;
} else
result = {
value: temp,
label: obj.label,
};
}
return result;
}
const postDate = new Date('2020-12-17 23:50:00+0700');
console.log(diff(postDate));
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);
let delta = Math.floor(Math.abs(start.getTime() - end.getTime()) / 1000);
let hours = Math.floor(delta / 3600);
delta -= hours * 3600;
let minutes = Math.floor(delta / 60);
delta -= minutes * 60;
let seconds = delta;
if (hours.toString().length === 1) {
hours = `0${hours}`;
}
if (minutes.toString().length === 1) {
minutes = `0${minutes}`;
}
if (seconds.toString().length === 1) {
seconds = `0${seconds}`;
}
const recordingTime = `${hours}:${minutes}:${seconds}`;
2021 version
Inspired with Alnitak's and RienNeVaPlus's answers.
Calculates since and until automatically (see examples below).
const timeUnits = {
year: 31536e6,
month: 2592e6,
week: 6048e5,
day: 864e5,
hour: 36e5,
minute: 6e4,
second: 1e3,
};
const timeUnitsNamesShort = {
year: 'y',
month: 'm',
week: 'w',
day: 'd',
hour: 'h',
minute: 'm',
second: 's',
};
const isFuture = (date) => date > Date.now();
const dateDiffStructure = (date, units = timeUnits) => {
let delta = Math.abs(date - Date.now());
return Object.entries(units).reduce((acc, [key, value]) => {
acc[key] = Math.floor(delta / value);
delta -= acc[key] * value;
return acc;
}, {});
};
const dateDiffStructureToString = (date, diffStructure, values, short) => {
const diffStructureEntries = values
? Object.entries(diffStructure).filter(([key, value]) => values.includes(key) && value)
: Object.entries(diffStructure).filter(([, value]) => value);
if (!diffStructureEntries.length) return 'just now';
const suffix = isFuture(date) ? 'left' : 'ago';
const diffString = diffStructureEntries.reduce((acc, [key, value]) => {
const timeUnit = short
? timeUnitsNamesShort[key]
: value > 1
? ` ${key}s`
: ` ${key}`;
acc = acc ? `${acc} ` : '';
return `${acc}${value}${timeUnit}`;
}, '');
return `${diffString} ${suffix}`;
};
const getDateDiff = (date, values, short) => {
const diffStructure = dateDiffStructure(date);
return dateDiffStructureToString(date, diffStructure, values, short);
};
Tests and examples:
const timeUnits = {
year: 31536e6,
month: 2592e6,
week: 6048e5,
day: 864e5,
hour: 36e5,
minute: 6e4,
second: 1e3,
};
const timeUnitsNamesShort = {
year: 'y',
month: 'm',
week: 'w',
day: 'd',
hour: 'h',
minute: 'm',
second: 's',
};
const isFuture = (date) => date > Date.now();
const dateDiffStructure = (date, units = timeUnits) => {
let delta = Math.abs(date - Date.now());
return Object.entries(units).reduce((acc, [key, value]) => {
acc[key] = Math.floor(delta / value);
delta -= acc[key] * value;
return acc;
}, {});
};
const dateDiffStructureToString = (date, diffStructure, values, short) => {
const diffStructureEntries = values ?
Object.entries(diffStructure).filter(([key, value]) => values.includes(key) && value) :
Object.entries(diffStructure).filter(([, value]) => value);
if (!diffStructureEntries.length) return 'just now';
const suffix = isFuture(date) ? 'left' : 'ago';
const diffString = diffStructureEntries.reduce((acc, [key, value]) => {
const timeUnit = short ?
timeUnitsNamesShort[key] :
value > 1 ?
` ${key}s` :
` ${key}`;
acc = acc ? `${acc} ` : '';
return `${acc}${value}${timeUnit}`;
}, '');
return `${diffString} ${suffix}`;
};
const getDateDiff = (date, values, short) => {
const diffStructure = dateDiffStructure(date);
console.log(`dateDiffStructure(${JSON.stringify(date)}) //`, diffStructure);
return dateDiffStructureToString(date, diffStructure, values, short);
};
const tests = [
['After tomorrow', [new Date(Date.now() + 8.64e7 + 1e6)]],
['Yesterday', [new Date(Date.now() - 8.64e7)]],
['Past', [new Date(Date.now() * Math.random())]],
['Future short', [new Date(Date.now() * (Math.random() + 1)), ['year', 'month', 'day'], true]],
['Now', [Date.now()]]
];
tests.forEach(([text, args]) => {
console.log(`${text}:`);
console.group();
console.log(`getDateDiff(${args.map(item => JSON.stringify(item)).join(', ')}) //`, getDateDiff(...args));
console.groupEnd();
});
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
};
}
let result = getTimeRemaining(endTime) // pass the end date into the func
you can also find out the diff between two dates time by easily change the func parameters to
function getTimeRemaining(endtime,startime){
const total = Date.parse(endtime) - Date.parse(startime);
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
};
}
let result = getTimeRemaining(endTime,startTime)
The result will be like
days: 0,
hours: 1,
minutes: 0,
seconds: 0,
total: 3600000
Here’s that answer in TypeScript without mutation. Also has a 2-digit seconds handler.
const maybeAddLeadingZero = (number: number): string => [String(number).length === 1 ? '0' : '', number].join('');
const timeRemaining = (endDate: Date): string => {
const deltaInSeconds = Math.abs(Date.now() - endDate.valueOf()) / 1000;
const days = Math.floor(deltaInSeconds / 86400);
const deltaMinusDaysInSeconds = deltaInSeconds - days * 86400;
const hours = Math.floor(deltaMinusDaysInSeconds / 3600) % 24;
const deltaMinusHoursInSeconds = deltaMinusDaysInSeconds - hours * 3600;
const minutes = Math.floor(deltaMinusHoursInSeconds / 60) % 60;
const twoDigitMinutes = maybeAddLeadingZero(minutes);
const deltaMinusMinutesInSeconds = deltaMinusHoursInSeconds - minutes * 60;
const seconds = Math.floor(deltaMinusMinutesInSeconds % 60);
const twoDigitSeconds = maybeAddLeadingZero(seconds);
return `${hours}:${twoDigitMinutes}:${twoDigitSeconds}`
}
const twentyFourHoursInTheFuture = new Date(new Date().getTime() + 24 * 60 * 60 * 1000)
// example implementation
setInterval(() => {
const deriveTimeRemaining = timeRemaining(twentyFourHoursInTheFuture);
document.body.innerHTML = "";
document.write(`<h1>${deriveTimeRemaining}</h1>`)
}, 1000 / 60) // 60 FPS
We can do it by simple method
/*Declare the function */
function Clock(){
let d1 = new Date("1 Jan 2021");
let d2 = new Date();
let difference = Math.abs(d1 - d2); //to get absolute value
//calculate for each one
let Days = Math.floor(difference / ( 1000 * 60 * 60 * 24 ));
let Hours = Math.floor((difference / ( 1000 * 60 * 60 )) % 24);
let Mins = Math.floor((difference / ( 1000 * 60 )) % 60);
let Seconds = Math.floor((difference / ( 1000 )) % 60);
//getting nodes and change the text inside
let getday = document.querySelector(".big_text_days");
let gethour = document.querySelector(".big_text_hours");
let getmins = document.querySelector(".big_text_mins");
let getsec = document.querySelector(".big_text_sec");
getday.textContent = Check_Zero(Days);
gethour.textContent = Check_Zero(Hours);
getmins.textContent = Check_Zero(Mins)
getsec.textContent = Check_Zero(Seconds);
}
//call the funcion for every 1 second
setInterval(Clock , 1000);
//check and add zero in front, if it is lessthan 10
function Check_Zero(mytime){
return mytime < 10 ? "0"+mytime : mytime;
}
*{
padding: 0px;
margin: 0px;
box-sizing: border-box;
}
body{
max-width: 900px;
margin: 0px auto;
background-color:whitesmoke;
background-size: cover;
display: flex;
flex-direction: column;
align-items: center;
margin-top: 5rem;
}
.main_container{
display: flex;
flex-wrap: wrap;
justify-content: center;
}
h1{
font-size: 3rem;
color: #3D4B72;
}
.big_text_days , .big_text_hours , .big_text_mins , .big_text_sec{
font-size: 2rem;
font-weight: bold;
line-height: 2;
color: #AC7591;
text-align: center;
}
p{
padding: 20px 0px 20px 0px;
font-size: 3rem;
text-align: center;
}
.spantext{
color: #103c28;
margin: 0px 3rem;
font-size: 2rem;
font-style: italic;
}
.text_sec{
color : #005259;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="description" content="Responsive site">
<meta name="keywords" content="HTML,CSS,JS">
<meta name="author" content="Ranjan">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Home</title>
<link href="https://fonts.googleapis.com/css?family=Alfa+Slab+One|Bree+Serif|Exo|Exo+2|Lato|Mansalva|Playfair+Display&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.2.0/css/all.css" integrity="sha384-hWVjflwFxL6sNzntih27bfxkr27PmbbK/iSvJ+a4+0owXq79v+lsFkW54bOGbiDQ" crossorigin="anonymous">
</head>
<body>
<section>
<h1>CountDown Timer</h1>
</section>
<section>
<div class="main_container">
<div class="days_container">
<p class="big_text_days">1</p>
<span class="spantext spantextdays">Days</span>
</div>
<div class="hours_container">
<p class="big_text_hours">1</p>
<span class="spantext spantexthours">Hours</span>
</div>
<div class="mins_container">
<p class="big_text_mins">1</p>
<span class="spantext spantextmins">Minutes</span>
</div>
<div class="sec_container">
<p class="big_text_sec text_sec">1</p>
<span class="spantext spantextsec">Seconds</span>
</div>
</div>
</section>
</body>
</html>

Categories