I would like to create a countdown timer for my resource. An example for this I took from Quasimodo's clone answer of this page.
From the code, I took some elements, since I only need minutes and seconds. And I don't need a 30 minute mark.
The code works great, but unlike the author of the question, I need the start to start and end at 1 minute of the next hour.
The changes that I made did not lead to the desired result:
secsRemaining = 3600 - (time.getUTCMinutes()+1)%60 * 60 - time.getUTCSeconds(),
and
mins = (Math.floor(secsRemaining / 60)+60),
This gave a result, but not the one that is needed. When the time on the clock becomes 00 minutes, then the code becomes 60 minutes and 00+ seconds. I need, for example, at 14:00:59 the timer has the values 00:01, and when 14:01:01 the timer has the values 59:59.
Please let me know how it can be changed to achieve the desired result. Perhaps you have a link to solutions. I couldn't find it on the Internet.
Code I am using:
var byId = document.getElementById.bind(document);
function updateTime() {
var time = new Date(),
secsRemaining = 3600 - (time.getUTCMinutes()) % 60 * 60 - time.getUTCSeconds(),
mins = (Math.floor(secsRemaining / 60)),
secs = secsRemaining % 60;
byId('min-part').textContent = mins;
byId('sec-part').textContent = secs;
setTimeout(updateTime, 1000 - (new Date()).getUTCMilliseconds()).toLocaleString();
}
updateTime();
<div>Time left before update: <span id="min-part"></span>:<span id="sec-part"></span></div>
Here is how I would do it
Generating a date at the next hour and 1 minutes
Calculating the number of millisecond between the current date and the next date
Display the time remaining
const minutes = document.getElementById('minutes')
const seconds = document.getElementById('seconds')
setInterval(() => {
const now = new Date()
const nextHours = new Date(now.getFullYear(), now.getMonth(), now.getDate(), now.getHours() + 1, 1)
const nbMilisec = (nextHours - now)
const nbMinutes = parseInt((nbMilisec / 1000 / 60) % 60)
const nbSeconds = parseInt((nbMilisec / 1000) % 60)
minutes.innerHTML = String(nbMinutes).padStart(2, '0')
seconds.innerHTML = String(nbSeconds).padStart(2, '0')
}, 1000)
<div id="time">
Time left before update : <span id="minutes"></span> : <span id="seconds"></span>
</div>
If I understood well your needs, this should be the code you need:
var byId = document.getElementById.bind(document);
function updateTime()
{
var
time = new Date(),
// You need an hour of countdown, so 30 becomes 60
secsRemaining = 3600 - (time.getUTCMinutes()+60)%60 * 60 - time.getUTCSeconds(),
// integer division
// you want the timer to "end" at minute 1, so add 1 minute to the minutes counter
mins = (Math.floor(secsRemaining / 60) + 1) % 60,
secs = secsRemaining % 60
;
byId('min-total').textContent = secsRemaining;
byId('min-part').textContent = mins;
byId('sec-part').textContent = secs;
// let's be sophisticated and get a fresh time object
// to calculate the next seconds shift of the clock
setTimeout( updateTime, 1000 - (new Date()).getUTCMilliseconds() );
}
updateTime();
Related
I have a problem, where I try to find the number of hours and minutes after I had last collected the item. For example, if I had collected the item 1 minute ago, the code should be able to print out the remaining time left to collect the item again(23 h and 59 m) in this format. Till now, I have worked out this much:
UserJSON is a JSON file with the user's name and the time of their last claim
let deltaHour = Math.floor(new Date().getTime() - UserJSON[message.author.id].lastclaim) / (60 * 60 * 24)
let deltaRealHour = Math.floor(deltaHour)
let deltaMin = ((deltaHour % 1) / 100) * 60
Please help me out.
Here is a possible solution.
You can use the function I wrote before (timeUntilNextClaim()), supply it with the last time that your user claimed the item (in epoch seconds) and it will return to you the delta milliseconds until the item can be claimed.
You can then use the second funciton I wrote for you (toHrsAndMinutes) to turn milliseconds into hours and minutes (rounded down of course).
Please let me know if you have any questions or would like any more help with this. I'd be happy to help.
function timeUntilNextClaim(LastClaim) {
/* this function takes an epoch time of the
last time the user claimed the item as an argument and
returns (in ms) the time until they can pick up the
item again */
let now = new Date();
// add 24 hours to last claim time to calculate next claim time
let timeTilClaim = (LastClaim + 8.64e7) - now;
if (timeTilClaim <= 0) {
return 0;
} else {
return timeTilClaim;
}
}
function toHrsAndMinutes(duration) {
// this function will return an array of [hours, minutes] of a duration specified in ms
var hours, minutes;
hours = Math.floor(duration / 3.6e6);
minutes = Math.floor((duration % 3.6e6) / 60000);
return [hours, minutes];
}
function test() {
// tests / Example Usage
let usrLastClaimTime = new Date() - 20160000; // lets pretend they claimed it last 5.6 hours ago
let now = new Date();
let msTilNextClaim = timeUntilNextClaim(usrLastClaimTime);
let hoursTilClaim, minsTilClaim;
[hoursTilClaim, minsTilClaim] = toHrsAndMinutes(msTilNextClaim);
console.log(`The current time is ${now}`);
console.log(`The item was last claimed at ${Date(usrLastClaimTime)}`);
console.log(`You can claim again in ${hoursTilClaim} Hours and ${minsTilClaim} Minutes`);
}
test();
getTime() is milliseconds since Jan 1, 1970, 00:00:00.000 GMT
let lastclaim = 1632196398605;
let delta = (new Date() - new Date(lastclaim)) / (60 * 1000 * 60);
let deltaHrs = Math.floor(delta);
let deltaMins = Math.floor((delta % 1) * 60);
console.log(`deltaHrs:`, deltaHrs);
console.log(`deltaMins:`, deltaMins);
My friend has given me files of his website to clone and make my own version, everything works as intended except for this time interval function. It works perfectly fine on my friends website, however on mine I found the countdown goes to zero, refreshes the page and doesn't reset, causing the page to reload constantly
var x = setInterval(function() {
var thing = parseInt($('#quest_reset').val());
thing = thing * 1000;
var now = new Date().getTime();
var distance = thing - now;
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);
document.getElementById("hours").innerHTML = hours
document.getElementById("minutes").innerHTML = minutes
document.getElementById("seconds").innerHTML = seconds
if (distance < 0) {
console.log(distance)
clearInterval(x);
document.getElementById("hours").innerHTML = 0
document.getElementById("minutes").innerHTML = 0
document.getElementById("seconds").innerHTML = 0
location.reload();
}
}, 1000);
The original value of thing is 1628380822, which would mean the value of #quest_reset would also be 1628380822 I found the value of now is much larger than thing
How come this works fine on my friends website but not on mine?
I guess that you code is fine, but here is my version. Instead of all the calculations you can use the Date object.
Here I define a future date by creating a new date and add 20 seconds to it. This is the timestamp that you compare against. This could also be a fixed number -- like the thing that you refer to.
In the function checktime the ´diffdate´ is the difference between the future date and now. If diff is less then 0 diffdate is set to 0, the interval is cleared and you can then reload or whatever. As the last thing (instead of repeating the same code) in the function the hour, minutes and seconds are set in the HTML elements.
All timestamps in the browser will start at Jan 01 1970 00:00:00 GMT. Try to console.log(new Date(0)). Your thing is a number of milliseconds -- probably the difference or a period defined by something. That is why thing is mush smaller than new Date().getTime() because that is the number of milliseconds from Jan 01 1970 and until now.
var h = document.getElementById("hours");
var m = document.getElementById("minutes");
var s = document.getElementById("seconds");
var futuredate = new Date();
futuredate.setSeconds(futuredate.getSeconds() + 20);
const checktime = function() {
let now = new Date();
let diffdate = new Date(futuredate - now);
let zero = new Date(0);
if (diffdate.getTime() < 0) {
diffdate = new Date(0);
clearInterval(x);
console.log('reload!');
}
h.innerText = diffdate.getHours() - zero.getHours();
m.innerText = diffdate.getMinutes() - zero.getMinutes();
s.innerText = diffdate.getSeconds() - zero.getSeconds();
};
var x = setInterval(checktime, 1000);
<div>
<span id="hours"></span>
<span id="minutes"></span>
<span id="seconds"></span>
</div>
I have beem looking for a code like this for a few days now. I did search a lot on the forum and found a bunch of threads about what I need but I couldn't get them to work (I have 0 expericnce in JS).
The code below does what I need, in a way.
It gives a negative value if the start time is, for example, 21:00 and the end time is 09:00.
Can anyone help me set it to positive? (I think it's related to beeing one day before, not sure thought).
<input type="time" id="start" value="21:00" >
<input type="time" id="end" value="09:00" >
<input id="diff">
<script>
var start = document.getElementById("start").value;
var end = document.getElementById("end").value;
document.getElementById("start").onchange = function() {diff(start,end)};
document.getElementById("end").onchange = function() {diff(start,end)};
function diff(start, end) {
start = document.getElementById("start").value; //to update time value in each input bar
end = document.getElementById("end").value; //to update time value in each input bar
start = start.split(":");
end = end.split(":");
var startDate = new Date(0, 0, 0, start[0], start[1], 0);
var endDate = new Date(0, 0, 0, end[0], end[1], 0);
var diff = endDate.getTime() - startDate.getTime();
var hours = Math.floor(diff / 1000 / 60 / 60);
diff -= hours * 1000 * 60 * 60;
var minutes = Math.floor(diff / 1000 / 60);
return (hours < 9 ? "0" : "") + hours + ":" + (minutes < 9 ? "0" : "") + minutes;
}
setInterval(function(){document.getElementById("diff").value = diff(start, end);}, 1000); //to update time every second (1000 is 1 sec interval and function encasing original code you had down here is because setInterval only reads functions) You can change how fast the time updates by lowering the time interval
</script>
PS: I found this code in here Difference between two html time inputs
Thanks in advance,
eLy
There are 2 possible solutions based on your requirement.
Start: 11AM, End: 9AM
If you want the output to be 2 hours,
var diff = Math.abs(endDate.getTime() - startDate.getTime());
If you want the output to be 22 hours,
var diff = endDate.getTime() - startDate.getTime();
if (diff < 0) {
diff += 24 * 1000 * 60 * 60;
}
What is the best way to get time for recent notifications (relative to current time) in an application, which are 5 sec ago, 10 sec ago or 7 hr 32 min ago?
In other words, I have a Date Object (in format 2019-03-12T10:05:32.257) which is for example 3 hr 6 min 9 sec ago from current time, I am wondering if there is a clean way to achieve the magic numbers 3, 6, 9 and display in html.
More cleaner way and generic implementation that I see to approach this problem could be.
Get the difference of date object in seconds converted as a first step
Then check for whether it could be fit into
years(divide by 31536000)
months(divide by 2592000)
days(divide by 86400)
hours(divide by 3600)
minutes(divide by 60)
function timesAgo(date) {
var seconds = Math.floor((new Date() - date) / 1000); // get the diffrence of date object sent with current date time of the system time
var interval = Math.floor(seconds / 31536000); // divide seconds by seconds in avg for a year to get years
//conditioning based on years derived above
if (interval > 1) {
return interval + " years";
}
interval = Math.floor(seconds / 2592000); // months check similar to years
if (interval > 1) {
return interval + " months";
}
interval = Math.floor(seconds / 86400); // days check similar to above
if (interval > 1) {
return interval + " days";
}
interval = Math.floor(seconds / 3600); // hours check
if (interval > 1) {
return interval + " hours";
}
interval = Math.floor(seconds / 60); // minutes check
if (interval > 1) {
return interval + " minutes";
}
return Math.floor(seconds) + " seconds"; // seconds check at the end
}
var withYears = new Date('August 19, 1999 23:15:30');
var withMonths = new Date('March 19, 2019 23:15:30');
var withDays = new Date('May 1, 2019 23:15:30');
var withPreviousDay = new Date('May 5, 2019 23:15:30');
var withHours = new Date('May 6, 2019 10:15:30');
console.log(timesAgo(withYears));
console.log(timesAgo(withMonths));
console.log(timesAgo(withDays));
console.log(timesAgo(withPreviousDay));
console.log(timesAgo(withHours));
Easier way If your using Angular and Moment is to use fromNow() function - Link
console.log(moment([2007, 0, 29]).fromNow(true)); // 12 years
console.log(moment([2007, 0, 29]).fromNow()); // 12 years ago
<script data-require="moment.js#*" data-semver="2.18.0" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.0/moment.min.js"></script>
If you need an Angular Pipe check this times-ago-pipe
I guess you are trying to find the difference between two Date objects.
First, you can convert them to Date objects, followed by using getTime() to get it in milliseconds. After which, you subtract both date objects to get the time difference, and then divide it by 1000 to get the results in seconds.
const targetDate = new Date('2019-03-12T10:05:32.257').getTime();
const current = new Date().getTime();
const differenceInSeconds = (current - targetDate) / 1000;
From there, you can convert it to your required format (hours, minutes, and seconds).
And in order to convert them into hours, minutes and seconds,
const hours = Math.floor(differenceInSeconds / 3600);
const minutes = Math.floor(differenceInSeconds % 3600 / 60);
const seconds = Math.floor(differenceInSeconds % 3600 % 60);
This is how the end result will be like:
const targetDate = new Date('2019-03-12T10:05:32.257').getTime();
const current = new Date().getTime();
const differenceInSeconds = (current - targetDate) / 1000;
const hours = Math.floor(differenceInSeconds / 3600);
const minutes = Math.floor(differenceInSeconds % 3600 / 60);
const seconds = Math.floor(differenceInSeconds % 3600 % 60);
const result = `${hours} hr ${minutes} min ${seconds} sec`
console.log(result);
I have 2 dates in ISO format like so:
startDate: "2018-09-14T00:20:12.200Z"
endDate: "2018-09-16T00:18:00.000Z"
What I'm trying to do is calculate the difference between those 2 days. So with the given dates it would be 1 Day, 21 Hours, 47 Minutes and 40 Seconds (pardon me if the subtraction is not correct).
Tried to do using the following:
const start = new Date(startDate).getTime();
const end = new Date(endDate).getTime();
return Math.abs(end - start).toString();
However this doesn't seem to work.
Any clues?
The following works. Things to note:
getTime() is not needed as the new Date() constructor returns the time in milliseconds.
The date should always be in RFC2822 or ISO formats, else it becomes useless across various browsers, even while using moment.js.
If you can use moment.js, Get time difference using moment.
Refer this to know why only the standardized formats need to be used.
var unitmapping = {"days":24*60*60*1000,
"hours":60*60*1000,
"minutes":60*1000,
"seconds":1000};
function floor(value)
{
return Math.floor(value)
}
function getHumanizedDiff(diff)
{
return floor(diff/unitmapping.days)+" days "+
floor((diff%unitmapping.days)/unitmapping.hours)+" hours "+
floor((diff%unitmapping.hours)/unitmapping.minutes)+" minutes "+
floor((diff%unitmapping.minutes)/unitmapping.seconds)+" seconds "+
floor((diff%unitmapping.seconds))+" milliseconds";
}
console.log(getHumanizedDiff(new Date("2018-09-16T00:18:00.000Z") - new Date("2018-09-14T00:20:12.200Z")));
console.log(getHumanizedDiff(new Date("2018-09-16T00:18:00.000Z") - new Date("2018-09-04T00:20:02.630Z")));
console.log(getHumanizedDiff(new Date("2018-09-17T00:16:04.000Z") - new Date("2018-09-14T00:20:12.240Z")));
var startDate = "2018-09-14T00:20:12.200Z"
var endDate = "2018-09-16T00:18:00.000Z"
const start = new Date(startDate).getTime();
const end = new Date(endDate).getTime();
const milliseconds = Math.abs(end - start).toString()
const seconds = parseInt(milliseconds / 1000);
const minutes = parseInt(seconds / 60);
const hours = parseInt(minutes / 60);
const days = parseInt(hours / 24);
const time = days + ":" + hours % 24 + ":" + minutes % 60 + ":" + seconds % 60;
console.log(time)
yBrodsky's suggestion to use moment.js is probably the best idea, but if you're curious how to do the math here, it would go something like this:
const start = new Date(startDate).getTime();
const end = new Date(endDate).getTime();
let seconds = Math.round(Math.abs(end - start) / 1000); // We'll round away millisecond differences.
const days = Math.floor(seconds / 86400);
seconds -= days * 86400;
const hours = Math.floor(seconds / 3600);
seconds -= hours * 3600;
minutes = Math.floor(seconds / 60);
seconds -= minutes * 60;
This leaves you with hours, minutes, and seconds as numbers that you can format into a string result however you like.