I found a countdown that is suitable for my web-project. I want that the countdown restarts every Friday at 9 am. Could someone give me a hint? Here is the code:
(function(){
const days = document.getElementById("days");
const hours = document.getElementById("hours");
const minutes = document.getElementById("minutes");
const seconds = document.getElementById("seconds");
const currentDate = new Date().getFullYear();
const concertDate = new Date(`June 19 ${currentDate} 09:00:00`);
function updateCountdown() {
const currentTime = new Date();
const diff = concertDate - currentTime;
const d = Math.floor(diff / 1000 / 60 / 60 / 24);
const h = Math.floor(diff / 1000 / 60 / 60) % 24;
const m = Math.floor(diff / 1000 / 60) % 60;
const s = Math.floor(diff / 1000) % 60;
days.innerHTML = d;
hours.innerHTML = h < 10 ? "0" + h : h;
minutes.innerHTML = m < 10 ? "0" + m : m;
seconds.innerHTML = s < 10 ? "0" + s : s;
}
setInterval(updateCountdown, 1000);
})();
Here is how I would do it. In the countdown function, add an if statement that checks whether the diff <= 0 - if it is (countdown expired), simply add one week of time to the concertDate, and the new countdown starts.
For this to work, firstly you have to change the concertDate declaration to let concertDate to allow it to be changed later on. And also, you need to use .getTime() for the concert that will give you the time of that date in miliseconds (this makes adding one week of time at the end possible).
(function(){
const days = document.getElementById("days");
const hours = document.getElementById("hours");
const minutes = document.getElementById("minutes");
const seconds = document.getElementById("seconds");
const currentDate = new Date().getFullYear();
let concertDate = new Date(`June 19 ${currentDate} 09:00:00`).getTime();
function updateCountdown() {
const currentTime = new Date();
const diff = concertDate - currentTime;
const d = Math.floor(diff / 1000 / 60 / 60 / 24);
const h = Math.floor(diff / 1000 / 60 / 60) % 24;
const m = Math.floor(diff / 1000 / 60) % 60;
const s = Math.floor(diff / 1000) % 60;
days.innerHTML = d;
hours.innerHTML = h < 10 ? "0" + h : h;
minutes.innerHTML = m < 10 ? "0" + m : m;
seconds.innerHTML = s < 10 ? "0" + s : s;
if (diff <= 0) {
concertDate = concertDate + (1000 * 3600 * 24 * 7); //add one week to concert date
}
}
setInterval(updateCountdown, 1000);
})();
Hope that helps!
You can use [cron]: https://www.npmjs.com/package/cron;
Your cron time should be like 0 9 * * 5
Related
here
I want the timer script that I made to follow the time on my pc, where is the wrong part of the code, please correct the wrong part of the code, thank you
enter code here
let countdown = new Date (new Date().getHours()
+ 1,0,1 );
let $hours = document.getElementById('hours');
let $minutes = document.getElementById('minutes');
let $seconds =document.getElementById('seconds')
setInterval(function() {
var now = new Date();
var timeleft = (countdown , now) / 1000;
updateclock(timeleft);
},1000);
function updateclock(remainingTime){
let hours = Math.floor(remainingTime / 3600) %
24;
remainingTime -= hours * 3600;
let minutes = Math.floor(remainingTime / 60) %
60;
remainingTime -= minutes * 60
let seconds = Math.floor(remainingTime % 60);
$hours.innerHTML = Number(hours);
$minutes.innerHTML = Number(minutes);
$seconds.innerHTML = Number(seconds);
}
function Number (Number) {
return Number < 10 ? + Number : Number;
}
subtracting one value from another does not reduce original variables, unless you explicitly assign result to one of them
anyway, the main problem was (countdown , now) statement, which should be actually: (countdown.valueOf() - now.valueOf())
let countdown = new Date ();
countdown.setHours(countdown.getHours()+1);
let $hours = document.getElementById('hours');
let $minutes = document.getElementById('minutes');
let $seconds =document.getElementById('seconds')
setInterval(function() {
var now = new Date();
var timeleft = (countdown.valueOf() - now.valueOf()) / 1000;
updateclock(timeleft);
},1000);
function updateclock(remainingTime){
remainingTime = parseInt(remainingTime, 10);
let seconds = remainingTime % 60;
remainingTime = Math.floor(remainingTime / 60);
let minutes = remainingTime % 60;
remainingTime = Math.floor(remainingTime / 60);
let hours = remainingTime;
$hours.innerHTML = Number(hours);
$minutes.innerHTML = Number(minutes);
$seconds.innerHTML = Number(seconds);
}
function Number (number) {
return (number >=0 && number < 10) ? ("0" + number) : number;
}
<span id="hours"></span> : <span id="minutes"></span> : <span id="seconds"></span>
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}`
);
how do I get, for example, the date of next monday and the time 5:30PM, and calculate the difference between current date and time and that date and time?
if I run it now at 8/28/2020 17:35, it should give me 8/31/2020 17:30 and the difference 2 days 23 hours 55 minutes.
I hope this help:
// takes dayIndex from Sunday(0) to Saturday(6)
const getNextDay = (dayIndex) => {
const today = new Date();
today.setDate(
today.getDate() + ((dayIndex - 1 - today.getDay() + 7) % 7) + 1
);
today.setHours(17, 30, 00);
return today;
};
const getTimeleft = (dateNow, dateFuture) => {
let seconds = Math.floor((dateFuture - dateNow) / 1000);
let minutes = Math.floor(seconds / 60);
let hours = Math.floor(minutes / 60);
let 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;
return `${days} days ${hours} hours ${minutes} minutes`;
};
const now = new Date();
const nextMonday = getNextDay(1);
const timeleft = getTimeleft(now, nextMonday);
console.log(nextMonday.toLocaleString());
console.log(timeleft);
You could use moment.js, it's a very useful library when it comes to dates:
<script src="https://momentjs.com/downloads/moment.js"></script>
<script>
const today = moment();
const nextMonday = moment().add(1, 'weeks').isoWeekday(1);
nextMonday.set({'hour': 17, 'minute': 30, 'seconds': 0});
console.log(nextMonday.toString());
const duration = moment.duration(nextMonday.diff(today));
const days = duration.asDays();
const hours = (days - Math.floor(days)) * 24;
const minutes = (hours - Math.floor(hours)) * 60;
console.log("days", Math.floor(days));
console.log("hours", Math.floor(hours));
console.log("minutes", Math.floor(minutes));
</script>
Here is the working example:
function nextWeekMonday(date)
{
var diff = date.getDate() - date.getDay() + (date.getDay() === 0 ? -6 : 1);
var currWeekMonday = new Date(date.setDate(diff));
return new Date(currWeekMonday.getTime() + 7 * 24 * 60 * 60 * 1000);
}
function getDateDifference(current, future) {
// get total seconds between the times
var delta = Math.abs(future - current) / 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;
return `${days} Days, ${hours} Hours, ${minutes} Minutes, ${seconds} Seconds`;
}
var curr = new Date; // get current date
var nextMonday = nextWeekMonday(curr);
console.log(getDateDifference(curr, nextMonday));
I am using javascript Date object trying to convert millisecond to how many hour, minute and second it is.
I have the currentTime in milliseconds
var currentTime = new Date().getTime()
and I have futureTime in milliseconds
var futureTime = '1432342800000'
I wanted to get difference in millisecond
var timeDiff = futureTime - currentTime
the the timeDiff was
timeDiff = '2568370873'
I want to know how many hours, minutes, seconds it is.
Could anyone help?
const secDiff = timeDiff / 1000; //in s
const minDiff = timeDiff / 60 / 1000; //in minutes
const hDiff = timeDiff / 3600 / 1000; //in hours
updated
function msToHMS( ms ) {
// 1- Convert to seconds:
let seconds = ms / 1000;
// 2- Extract hours:
const hours = parseInt( seconds / 3600 ); // 3,600 seconds in 1 hour
seconds = seconds % 3600; // seconds remaining after extracting hours
// 3- Extract minutes:
const minutes = parseInt( seconds / 60 ); // 60 seconds in 1 minute
// 4- Keep only seconds not extracted to minutes:
seconds = seconds % 60;
alert( hours+":"+minutes+":"+seconds);
}
const timespan = 2568370873;
msToHMS( timespan );
Demo
If you are confident that the period will always be less than a day you could use this one-liner:
new Date(timeDiff).toISOString().slice(11,19) // HH:MM:SS
N.B. This will be wrong if timeDiff is greater than a day.
Convert ms to hh:mm:ss
function millisecondsToHuman(ms) {
const seconds = Math.floor((ms / 1000) % 60);
const minutes = Math.floor((ms / 1000 / 60) % 60);
const hours = Math.floor((ms / 1000 / 3600 ) % 24)
const humanized = [
pad(hours.toString(), 2),
pad(minutes.toString(), 2),
pad(seconds.toString(), 2),
].join(':');
return humanized;
}
=
function msToHMS( duration ) {
var milliseconds = parseInt((duration % 1000) / 100),
seconds = parseInt((duration / 1000) % 60),
minutes = parseInt((duration / (1000 * 60)) % 60),
hours = parseInt((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 ;
}
Converts milliseconds to a string in the format hh:mm:ss. Here's my version:
function HHMMSSFromMilliseconds(ms) {
// 1- Convert to seconds:
var seconds = ms / 1000;
// 2- Extract hours:
var hours = parseInt(seconds / 3600); // 3600 seconds in 1 hour
seconds = parseInt(seconds % 3600); // extract the remaining seconds after extracting hours
// 3- Extract minutes:
var minutes = parseInt(seconds / 60); // 60 seconds in 1 minute
// 4- Keep only seconds not extracted to minutes:
seconds = parseInt(seconds % 60);
// 5 - Format so it shows a leading zero if needed
let hoursStr = ("00" + hours).slice(-2);
let minutesStr = ("00" + minutes).slice(-2);
let secondsStr = ("00" + seconds).slice(-2);
return hoursStr + ":" + minutesStr + ":" + secondsStr
}
let timespan = 23570 * 1000;
let formattedTime = HHMMSSFromMilliseconds(timespan);
console.log(formattedTime);
Convert millis to DD(days):HH:MM:SS
function formatTime(timeMS) {
const [MS_IN_SEC, SEC_IN_DAY, SEC_IN_HOUR, SEC_IN_MIN] = [1000, 86400, 3600, 60];
let seconds = Math.round(Math.abs(timeMS) / MS_IN_SEC);
const days = Math.floor(seconds / SEC_IN_DAY);
seconds = Math.floor(seconds % SEC_IN_DAY);
const hours = Math.floor(seconds / SEC_IN_HOUR);
seconds = Math.floor(seconds % SEC_IN_HOUR);
const minutes = Math.floor(seconds / SEC_IN_MIN);
seconds = Math.floor(seconds % SEC_IN_MIN);
const [dd, hh, mm, ss] = [days, hours, minutes, seconds]
.map(item => item < 10 ? '0' + item : item.toString());
return dd + ':' + hh + ':' + mm + ':' + ss;
}
The difference in time is in milliseconds:
Get time difference between two dates in seconds
to get the difference you have to use math.floor()
http://www.w3schools.com/jsref/jsref_floor.asp
var secDiff = Math.floor(timeDiff / 1000); //in s
var minDiff = Math.floor(timeDiff / 60 / 1000); //in minutes
var hDiff = Math.floor(timeDiff / 3600 / 1000); //in hours
var timediff = futureTime - currentTime
long seconds = (long) (timediff / 1000) % 60 ;
long minutes = (long) ((timediff / (1000*60)) % 60);
long hours = (long) ((timediff / (1000*60*60)) % 24);
if(hours>0)
time = hours+" hrs : "+minutes+" mins";
else if(minutes>0)
time = minutes+" mins";
else if(seconds>0)
time = seconds+" secs";
Here is a simple function
function simplifiedMilliseconds(milliseconds) {
const totalSeconds = parseInt(Math.floor(milliseconds / 1000));
const totalMinutes = parseInt(Math.floor(totalSeconds / 60));
const totalHours = parseInt(Math.floor(totalMinutes / 60));
const days = parseInt(Math.floor(totalHours / 24));
const seconds = parseInt(totalSeconds % 60);
const minutes = parseInt(totalMinutes % 60);
const hours = parseInt(totalHours % 24);
let time = '1s';
if (days > 0) {
time = `${days}d:${hours}h:${minutes}m:${seconds}s`;
} else if (hours > 0) {
time = `${hours}h:${minutes}m:${seconds}s`;
} else if (minutes > 0) {
time = `${minutes}m:${seconds}s`;
} else if (seconds > 0) {
time = `${seconds}s`;
}
return time;
}
Hi I am having a hard time making this countdown work for me. I am trying to make it count down to every sunday at 11:15am since that is when our church service starts. Can anyone pleaes help me? I have the code here.
function croAnim(){
// IF THERE'S A COUNTDOWN
if ($('ul.cro_timervalue').length !== 0) {
// GET ALL THE INSTANCES OF THE TIMER
$('ul.cro_timervalue').each(function() {
var $this = $(this),
timesets = $this.data('cro-countdownvalue'),
now = new Date(),
tset = Math.floor(now / 1000),
counter1 = timesets - tset;
// CALCULATE SECONDS
var seconds1 = Math.floor(counter1 % 60);
seconds1 = (seconds1 < 10 && seconds1 >= 0) ? '0'+ seconds1 : seconds1;
// CALCULATE MINUTES
counter1 =counter1/60;
var minutes1 =Math.floor(counter1 % 60);
minutes1 = (minutes1 < 10 && minutes1 >= 0) ? '0'+ minutes1 : minutes1;
// CALCULATE HOURS
counter1=counter1/60;
var hours1=Math.floor(counter1 % 24);
hours1 = (hours1 < 10 && hours1 >= 0) ? '0'+ hours1 : hours1;
// CALCULATE DAYS
counter1 =counter1/24;
var days1 =Math.floor(counter1);
days1 = (days1 < 10 && days1 >= 0) ? '0'+ days1 : days1;
// ADD THE VALUES TO THE CORRECT DIVS
$this.find('span.secondnumber').html(seconds1);
$this.find('span.minutenumber').html(minutes1);
$this.find('span.hournumber').html(hours1);
$this.find('span.daynumber').html(days1);
});
}
}
// CREATE A INTERVAL FOR THE TIMER
croInit = setInterval(croAnim, 100);
I answered a similar question about a week or so ago. I have a really simple countdown function already written. The trick is to modify it to get the next Sunday # 11:15 am, which I've written a function for.
var getNextSunday = function () {
var today = new Date(),
day = today.getDay(), // 1 for Mon, 2 for Tue, 3 for Wed, etc.
delta = 7 - day;
var sunday = new Date(today.getTime() + (delta * 24 * 3600 * 1000));
sunday.setHours(11);
sunday.setMinutes(15);
sunday.setSeconds(0);
return sunday;
}
var t = getNextSunday(),
p = document.getElementById("time"),
timer;
var u = function () {
var delta = t - new Date(),
d = delta / (24 * 3600 * 1000) | 0,
h = (delta %= 24 * 3600 * 1000) / (3600 * 1000) | 0,
m = (delta %= 3600 * 1000) / (60 * 1000) | 0,
s = (delta %= 60 * 1000) / 1000 | 0;
if (delta < 0) {
clearInterval(timer);
p.innerHTML = "timer's finished!";
} else {
p.innerHTML = d + "d " + h + "h " + m + "m " + s + "s";
}
}
timer = setInterval(u, 1000);
<h1 id="time"></h1>
This should be easy enough to adapt to fit your website's needs. The only tricky part might be my use of
h = (delta %= 24 * 3600 * 1000) / (3600 * 1000) | 0
delta %= ... returns delta, after performing the %=. This was just to save characters. If you don't like this, you can just separate the delta %= ... part:
delta %= 24 * 3600 * 1000;
h = delta / (3600 * 1000) | 0;
// ... do the same for the rest
This object uses a few semi-advanced javascript ideas (closures and * IIFE*) so hopefully it is easy-ish to understand. If you have any questions feel free to leave a comment.
var churchtime = (function (){
// Total seconds passed in the week by sunday 11:15am
var magic_number = 558900;
var now;
var rawtime = function (){
//updates now with the current date and time
now = new Date()
//Converts now into pure seconds
return (((((((now.getDay()-1)*24)+now.getHours())*60)+now.getMinutes())*60)+now.getSeconds());
};
//closure
return {
raw_countdown : function (){
return Math.abs(rawtime()-magic_number);
},
countdown : function(){
var time = Math.abs(rawtime()-magic_number)
var seconds = time % 60, time = (time - seconds)/60;
var minutes = time % 60, time = (time - minutes)/60;
var hours = time % 24, time = (time - hours)/24;
var days = time;
return [days,hours,minutes,seconds];
}
}
})(558900); //<- Total seconds passed in the week by sunday 11:15am
churchtime.raw_countdown()// returns the raw number of seconds until church
churchtime.countdown() // returns an array of time until church [days,hours,minutes,seconds]
Once you have an object like churchtime, it should be super easy to implement.
For example:
var churchtime = (function(magic_number) {
var now;
var rawtime = function() {
//updates now with the current date and time
now = new Date()
//Converts now into pure seconds
return (((((((now.getDay() - 1) * 24) + now.getHours()) * 60) + now.getMinutes()) * 60) + now.getSeconds());
};
//closure
return {
raw_countdown: function() {
return Math.abs(rawtime() - magic_number);
},
countdown: function() {
var time = Math.abs(rawtime() - magic_number)
var seconds = time % 60,
time = (time - seconds) / 60;
var minutes = time % 60,
time = (time - minutes) / 60;
var hours = time % 24,
time = (time - hours) / 24;
var days = time;
return [days, hours, minutes, seconds];
}
}
})(); //<- IIFE
AutoUpdate = function AutoUpdate() {
var time = churchtime.countdown();
document.getElementById("day").innerHTML = time[0];
document.getElementById("hour").innerHTML = time[1];
document.getElementById("min").innerHTML = time[2];
document.getElementById("sec").innerHTML = time[3];
setTimeout(AutoUpdate, 900); //Calls it's self again after .9 seconds
}(); //<- IIFE
<h1>Day:<span id="day"></span> Hour:<span id="hour"></span>
Minute:<span id="min"></span> second: <span id="sec"></span></h1>