I'm using date-fns. I need to create a countdown to the next 10th of the month.
For example, if today is 5th Feb, then the countdown should be to 10th Feb. If today is say 15th Feb, then it should count to 10th March, and so on.
How can I do this with date-fns or even with plain javascript?
You must first find the target date, like this one:
const today = startOfToday();
let target = setDate(today, 10);
if (isBefore(target, today)) {
target = addMonths(target, 1);
}
Then calculate time remaining until the target:
const diff = differenceInSeconds(target, new Date());
const days = Math.floor(diff / 86400);
const hours = Math.floor((diff - days * 86400) / 3600);
const minutes = Math.floor((diff - days * 86400 - hours * 3600) / 60);
const seconds = diff - days * 86400 - hours * 3600 - minutes * 60;
Use days, hours, minutes, seconds for create a countdown. Don't forget to import required functions from date-fns.
Related
I am getting the elapsed time in minutes, hours and days, between two dates, a past date and the current one, I already get this data, but I want this data to change as the minutes, days and hours increase. For example, when I get to 60 minutes, the time changes to 1 hour and the minutes go to 0, when 24 hours go by, these hours change to a day and the hours go back to 0, and so on, the data I get keeps increasing , how can I do this?
const calculateDate = () => {
const date = new Date('Sun Sep 01 2022 01:32:06 GMT-0500');
const currentDate = new Date();
const minutes= Math.floor((currentDate.getTime() - date.getTime()) / 1000 / 60);
const hours= Math.floor((currentDate.getTime() - date.getTime()) / 1000 / (3600));
const days= Math.floor((currentDate.getTime() - date.getTime()) / (1000*60*60*24));
}
With this, get the minutes, hours and days, but how would you update so that when you reach 60 minutes it goes to one hour and 24 hours to one day?
The JavaScript Date object has built in functions for what you want to do.
var now = new Date()
var h = now.getHours()
var m = now.getMinutes()
var s = now.getSeconds()
The new Date created in above example is set to the time it was created.
You can get the current time using the Date object itself:
var current = Date()
With your method you always see the full duration just in a different unit.
You have to use the modulo operator to get only the "missing part" (the remainder of the division) to the next unit:
const date = new Date('Sun Sep 01 2022 01:32:06 GMT-0500');
const currentDate = new Date();
const dateDiff = (currentDate.getTime() - date.getTime()) / 1000;
const seconds = Math.floor(dateDiff) % 60;
const minutes = Math.floor(dateDiff / 60) % 60;
const hours = Math.floor(dateDiff / (60 * 60)) % 24;
const days = Math.floor(dateDiff / (60 * 60 * 24));
I need to change my return time settings from hours to days.
I've tried to expand the hours but I keep getting errors.
let totalSeconds = (client.uptime / 1000);
let hours = Math.floor(totalSeconds / 3600);
totalSeconds %= 3600;
let minutes = Math.floor(totalSeconds / 60);
let seconds = totalSeconds % 60;
// Then you'll have hours, minutes and seconds ready to use.
let uptime = `${hours} hours, ${minutes} minutes and ${seconds} seconds`;
I just keep getting errors.
Converting hours to days would be extremely simple - you just divide by 24 and floor it:
var days = Math.floor(hours / 24);
Hopefully this helps!
Is it possible that in different Android devices time was measured differently?
In the database I save time in UTC
in the reactive native application, I save the time as new Date()
I COUNT THE DIFFERENCE OF TIME FOR TIMES IN THE SAME MOMENT
RESULTS:
the emulator is 0 days and 0 hours (OK)
the smartphone is -1 days and 23 hours (??)
let date = new Date(dateTimeDone);
var today = new Date();
today.setHours(today.getHours());
seconds = Math.floor((today - (date)) / 1000);
minutes = Math.floor(seconds / 60);
hours = Math.floor(minutes / 60);
days = Math.floor(hours / 24);
hours = hours - (days * 24);
i can image someone had donde this already or it can be considered a duplicated question, i've been searching for weeks and i can't figure out how to accomplish this.
I have a countdown made in js, the problem i'm facing is that when ever i test it in another country the times throw out different hours example.
i'm in centralamerica, end date is apr 16, 2018 23:59:59" if i test this in centralamerica it says 6 days and 10 hours remaining, if i run this in italy for example it says 6 days and 3 hours remaining, i need it to be equal all the time and that the timezone doesn´t affects, is this even possible, and please help on how to get it done.
the script i have is working but not the way i need to, i have a promo that will expire on "apr 16, 2018 23:59:59" so if it only has 5 hours remaining it shout say 5 hours remaining no matter where its been seeing from, but that is not happening.
$("#masterslider").append("<p id='demo'>.</p>")
$("#masterslider").append("<span> remaining time </span>")
//******************************** update date here ************************
var serverDate = new Date("apr 16, 2018 23:59:59");
var offset = serverDate.getTimezoneOffset();
serverDate = addOffset(serverDate, offset);
setInterval(function(){
updateCountdown();
}, 1000);
function addOffset(date, offset) {
var time = date.getTime() ;
return new Date(time + offset * 6000);
}
function updateCountdown() {
var userDate = new Date();
var distance = serverDate.getTime() - userDate.getTime();
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);
if(serverDate.getTime() > userDate.getTime()){
$('#demo').html( days +"day(s)"+ " / " + hours + "hour(s)" + minutes + "minutes(s)");
}
else
{
$("#demo").html(mas);
$("#masterslider span").hide();
}
}
</script>
I've checked and setting correct timezone for "event timestamp" works for me regardless local client timezone I use.
let targetDate = new Date("2018-04-11 23:59:59 GMT-0800");
let refreshDelayMs = 1000;
function updateCounter() {
let distance = (targetDate - new Date()) / 1000;
let seconds = Math.floor(distance % 60).toString().padStart(2, '0');
distance = distance / 60;
let minutes = Math.floor(distance % 60).toString().padStart(2, '0');
distance = distance / 60;
let hours = Math.floor(distance % 24).toString().padStart(2, '0');
let days = Math.floor(distance / 24).toString().padStart(2, '0');
document.querySelector('.counter').innerHTML = `${days} days ${hours}:${minutes}:${seconds}`;
setTimeout(updateCounter, refreshDelayMs);
}
updateCounter();
Remains: <span class="counter"></span>
You can use moment-timezone from CDN or use NPM
repl.it sample
const moment = require("moment-timezone");
function toTimeZone(time, offset) {
var format = 'YYYY/MM/DD HH:mm:ss ZZ';
return moment(time, format).utcOffset(offset).format(format);
}
toTimeZone("2018/04/10 15:37", "+0730")
Common headache, but each answer seems to be unique, I have some simple JS counting down until december 15th, this countdown works on each browser except I get 'NaN' for each day, hour, minute on safari.
<p id="clockdiv" class="decofont ">
<span class="days"></span>
<span class="hours"></span>
<span class="minutes"></span></p>
<!--302 D | 21 H | 48 M december 15 2017 -->
var deadline = '12 15 2017';
function getTimeRemaining() {
var t = Date.parse('12 15 2017') - Date.parse(new Date());
var seconds = Math.floor((t / 1000) % 60);
var minutes = Math.floor((t / 1000 / 60) % 60);
var hours = Math.floor((t / (1000 * 60 * 60)) % 24);
var days = Math.floor(t / (1000 * 60 * 60 * 24));
var time = {
'total': t,
'days': days,
'hours': hours,
'minutes': minutes,
'seconds': seconds
};
var output_time = document.getElementById('clockdiv');
output_time.innerHTML = days + ' D | ' + hours + ' H | ' + minutes + ' M';
setTimeout(getTimeRemaining, 60000);
}
getTimeRemaining(deadline);
Bonus points if you have a link to JS cross browser compatibility (common functions that don't work on all browsers). What is causing this to break on safari and what is the most simple alternative?
The root of your issue is that you are parsing a string and expecting all browsers to parse it the same. Parsing of date string is almost entirely implementation dependent, there is only one format (ISO 8601 extended) that ECMA-262 requires to be supported.
So in the line:
var t = Date.parse('12 15 2017') - Date.parse(new Date());
you should use the Date constructor. Also, you should not use Date.parse(new Date()), just use new Date or Date.now() so:
var t = new Date(2017,11,15) - new Date();
which will return the difference in milliseconds between the two dates:
console.log(new Date(2017,11,15) - new Date());
Also see Difference between dates in JavaScript.