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);
Related
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();
I have two sample unix timestamps that I'm trying to find the difference for in hours/minutes/seconds. One is a current time from TypeScript and one is an expiration time within 24 hours after. I just want to print out the time left until expiration.How do I go about this in TypeScript and Node?
current_time = 1633115367891
exp_time = 01633201203
You can convert unix timestamp to milliseconds timestamp and take their delta. Then convert the delta to hh:mm:ss format.
const current_time = 1633115367891,
exp_time = 1633201203,
diff = (exp_time * 1000) - current_time,
formatTime = (ms) => {
const seconds = Math.floor((ms / 1000) % 60);
const minutes = Math.floor((ms / 1000 / 60) % 60);
const hours = Math.floor((ms / 1000 / 3600) % 24);
return [hours, minutes, seconds].map(v => String(v).padStart(2,0)).join(':');
}
console.log(formatTime(diff));
I'm making a clock, that calculates the number of days based on the date that the user input.
Let's say the user input November 20, 2020.
However, the calculate was really off, especially, if I put today date (Jan 06, 2021), then calculate started with -6.
Please take a look and let me know where I went wrong with the calculation.
This is my javascript for it:
document.addEventListener('DOMContentLoaded', function() {
// console.log("js running");
var days = document.querySelector('.days span');
var hour = document.querySelector('.hour');
var min = document.querySelector('.min');
var second = document.querySelector('.second');
var startDate = new Date(2020, 11, 20);
days.innerText = Math.floor((new Date - startDate)/86400000);
countTime();
function countTime() {
let today = new Date();
let ms = (today - startDate) % 86400000;
hour.innerText = Math.floor(ms / 3600000);
min.innerText = Math.floor(ms % 3600000 / 60000);
second.innerText = Math.floor(ms % 3600000 % 60000 / 1000);
}
setInterval(countTime, 1000);
}, false);
In your example, the ms variable was the number of days, and you used it in every other calculation, instead of the actual time difference. You can convert the difference to seconds, and work from there:
document.addEventListener('DOMContentLoaded', function() {
const $ = document.querySelector.bind(document),
days = $('.days span'),
hour = $('.hour'),
min = $('.min'),
second = $('.second');
const startDate = new Date(2020, 11, 20);
countTime();
function countTime() {
const today = new Date(),
diffInSeconds = Math.floor((today - startDate) / 1000);
days.innerText = Math.floor(diffInSeconds / 86400);
hour.innerText = Math.floor(diffInSeconds % 86400 / 3600);
min.innerText = Math.floor(diffInSeconds % 3600 / 60);
second.innerText = Math.floor(diffInSeconds % 60);
}
setInterval(countTime, 1000);
});
<span class="days"><span></span></span> days
<span class="hour"></span> hours
<span class="min"></span> minutes
<span class="second"></span> seconds
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.
I wish to do a countdown to a specific date and hour (January 10, 2018, 19:30). Which in large part I am able to do. Below code shows the remaining days, hours, minutes and seconds.
The tricky bit is to get certain periods of time. The countdown should respond to the following:
1. on the deadline day and hour show the message 'Now going live'. Which is 10 January 2018 19:30.
2. That same day but BEFORE 19:30 it should say 'Going live tonight'
3. The complete day before the deadline day (from 00:00 to 23:59) it should say 'last day'
4. The complete days before that it should say 'many days to go'
Step 1 and 2 I managed, but I'm having trouble getting the complete day before the deadline day and the complete days before that. That's because I'm not able to define the complete day before the deadline day (and the days before that). Because it counts '1 day' as 1 day before 10 January 19:30 (so it also takes those hours/minutes of 19:30 into account).
Step 1 and 2 I managed in the if-loop, but I can't figure out how to do step 3 and 4. Step 3 should say something like 'count one day, but before 10 January 2018 00:00. So it should subtract that 19:30 to get to 9 januari 2018 00:00-23:59. And the same for step 4. Can someone fix my code?
// Get todays date and time
var now = new Date().getTime();
// Set the date we're counting down to
var countDownDate = new Date("Januari 10, 2018 19:30").getTime();
// Find the distance between now an the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Display the result
this.timeleft.text = days + "d " + hours + "h " + minutes + "m " + seconds + "s ";
// countdown day 19:30
if ((days == 0) && (hours == 0) && (minutes == 0)) {
this.countdown.text = "NOW GOING LIVE!";
// countday day 00:00 - 19.30
} else if ((days == 0) && (hours <= 19) && (minutes <= 30)) {
this.countdown.text = "GOING LIVE TONIGHT!";
// 9 January 00:00 - 23:59
} else if ((days <= 1) && (hours >= 19) && (minutes >= 30)) {
this.countdown.text = "LAST DAY";
// days before 10 January
} else if (days >= 1) {
this.countdown.text = "MANY DAYS TO GO";
}
Since the "deadline" is hard-coded, you can hard-code everything and end up with something very simple:
var now = new Date().getTime();
var lastDayThreshold = new Date("January 9, 2018 00:00").getTime();
var liveTonightThreshold = new Date("January 10, 2018 00:00").getTime();
var countDownDate = new Date("January 10, 2018 19:30").getTime();
if (now < lastDayThreshold) this.countdown.text = "MANY DAYS TO GO";
else if(now < liveTonightThreshold) this.countdown.text = "LAST DAY";
else if(now < countDownDate) this.countdown.text = "LIVE TONIGHT";
else this.countdown.text = "NOW GOING LIVE";
Alex's answer was indeed what I was after. Those 'treshhold times' did the trick. Was thinking about improving it though as now I have to hard-code three dates/times. Preferably I would like to only specify the countDownDate date/time. And then let both Threshold dates calculate themselves. I tried to do that in a way, but ran into a problem. I know how to specify one day (1000 * 60 * 60 * 24), so I could subtract this 'oneday' value to get to the day before. But I wasn't able to calculate the milliseconds for the specified time 19:30. In order to read the miilliseconds since the beginning of January 10 until January 10 19:30. If I were able to do that it would look something like this (though I know this is incorrect, but you'll get the idea):
var oneday = 1000 * 60 * 60 * 24;
var countDownDate = new Date("January 10, 2018 19:30").getTime();
var lastDayThreshold = new Date(countDownDate - oneday "00:00").getTime();
var liveTonightThreshold = new Date(countDownDate "00:00").getTime();
You'll see my problem: for lastDayTreshold I could subtract one day of the countdowndate but then it would consider that 19:30 the previous day, not 00:00. And for liveTonightThreshold I also couldn't specify that I mean 00:00 of the countdowndate.
Would there be a way of doing that? Then I would just have to specify the countdown day and time and the rest would figure them out themselves.