Timer with a prefixed date - javascript - javascript

I have implemented a timer counter with a given starting date. Everything is normal until the point in which I want it to show months/days/minutes/seconds. I see where it lacks logic in my code, so my question is: Is there an elegant way to deal with that (the division of the total seconds), or should I just go with nested endless if statements?
var deadline = "December 18 2016 08:00:00 GMT+0300";
function getTimeRemaining(endTime) {
var t = Date.parse(endTime) - 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) % 30 );
var months = Math.floor( t/(1000*60*60*24*30) );
return {
'total': t,
'months': months,
'days': days,
'hours': hours,
'minutes': minutes,
'seconds': seconds
};
}

Related

change days and hours by how time flies

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));

Date-fns: Countdown to a specific date

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.

jQuery/Javascript Calculate Difference beetween two dates in months, weeks, days, hours, minutes and seconds

I want to calculate the difference beetween two dates in Javascript in months, weeks, days, hours, minutes and seconds.
Problem:
Weeks and days aren't calculated properly.
I already tried to change .get...() into .getUTC...() but the difference was calculated wrong either.
var date = new Date("{% if holiday.is_now %}{{ holiday.end_date.isoformat }}{% else %}{{ holiday.end_date.isoformat }}{% endif %}");
function calcDate(a, b) {
var utc1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDay(), a.getHours(), a.getMinutes(), a.getSeconds());
var utc2 = Date.UTC(b.getFullYear(), b.getMonth(), b.getDay(), b.getHours(), b.getMinutes(), b.getSeconds());
return (utc2 - utc1) / 1000;
}
function convertDate(seconds){
var sec = Math.floor(seconds % 60);
var min = Math.floor(seconds / 60 % 60);
var hour = Math.floor(seconds / 60 / 60 % 24);
var diff = seconds / 60 / 60 / 24;
var months = Math.floor(diff / 30);
var weeks = Math.floor(diff / 7 % (30 / 7));
var days = Math.floor(diff % 7);
console.log(days);
return [months, weeks, days, hour, min, sec]
}
function add_countdown(sec){
$.each(convertDate(sec), function(i, element){
var selected = $("footer .countdown .counter#_counter_date_" + i);
selected.find("h1").text(element);
singular_pluralize(selected.find("p"), element);
})
}
function singular_pluralize(element, integer){
integer > 1 || integer == 0 ? element.text(element.attr("data-word-plural")) : element.text(element.attr("data-word-singular"));
}
var interval;
$("footer table td.a").on("click mouseup", function(){
clearInterval(interval);
date = new Date($(this).attr("data-date"));
$("footer #_foter_big_countdown_to_what").text("zu den " + $(this).attr("data-name").replace(/ /g, ''));
set_interval();
})
function set_interval(){
add_countdown(calcDate(new Date(), date));
interval = window.setInterval(function(){
var calc = calcDate(new Date(), date);
if (calc == 0)
holiday_begin();
else
add_countdown(calc);
}, 900);
}
function holiday_begin(){
$("footer .counter, footer .part#_footer_select_holiday").remove();
$("footer .darken h1._footer_big_countdown").html("Fröhliche Ferien!");
}
set_interval();
EDIT:
I found the solution. I had to use Math.round and I had to change a little bit:
function convertDate(seconds){
var sec = Math.round(seconds % 60);
var min = Math.round(seconds / 60 % 60);
var hour = Math.round(seconds / 60 / 60 % 24);
var diff = seconds / 60 / 60 / 24;
var months = Math.round(diff / 30);
var days = Math.round(diff % 30);
var weeks = Math.round(months / 4.3);
return [months, weeks, days, hour, min, sec]
}

Date and include time to countdown using javascript

i am trying below code for countdown to on exact date and time. I mean, i wants to make a under contractions website countdown date (include exact time). but date are not count downing. js code just showed me wrong count and not downing second, min, hours, day. This js code has problem, but i don't understand, exactly where is the problem.
Here is code:
(function init() {
function getTimeRemaining(endtime) {
var t = Date.parse(endtime) - Date.parse(new Date("03/13/2018 9:30 AM"));
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));
return {
'total': t,
'days': days,
'hours': hours,
'minutes': minutes,
'seconds': seconds
};
}
function initializeClock(endtime){
var timeinterval = setInterval(function(){
var t = getTimeRemaining(endtime);
document.querySelector(".days > .value").innerText=t.days;
document.querySelector(".hours > .value").innerText=t.hours;
document.querySelector(".minutes > .value").innerText=t.minutes;
document.querySelector(".seconds > .value").innerText=t.seconds;
if(t.total<=0){
clearInterval(timeinterval);
}
},1000);
}
initializeClock(((new Date()).getFullYear()+1) + "/1/1")
})();
I made some modifications to your code.
I added a displayTime() function that handles the time display.
initializeClock() now calls displayTime() directly when it's called, without waiting one second.
getTimeRemaining() now calculates the right time, by taking the current date into account, and not a random date: var t = Date.parse(endtime) - Date.parse(new Date());
function displayTime(date){
var t = getTimeRemaining(date);
document.querySelector(".days > .value").innerText = t.days;
document.querySelector(".hours > .value").innerText = t.hours;
document.querySelector(".minutes > .value").innerText = t.minutes;
document.querySelector(".seconds > .value").innerText = t.seconds;
return t;
}
function getTimeRemaining(endtime) {
var t = Date.parse(endtime) - 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));
return {
'total': t,
'days': days,
'hours': hours,
'minutes': minutes,
'seconds': seconds
};
}
function initializeClock(endtime) {
displayTime(endtime);
var timeinterval = setInterval(function() {
t = displayTime(endtime);
if (t.total <= 0) {
clearInterval(timeinterval);
}
}, 1000);
}
initializeClock("2018/03/13 09:30")
<div class="days"><span class="value"></span> days</div>
<div class="hours"><span class="value"></span> hours</div>
<div class="minutes"><span class="value"></span> minutes</div>
<div class="seconds"><span class="value"></span> seconds</div>
I think you are making this overly complicated. If you just start with a date and then every second, subtract one second from that start date, you're done.
var out = document.getElementById("output");
var start = new Date();
setInterval(function(){
start = new Date(start.getTime() - 1000);
out.textContent =
start.getHours() + " Hours, " + start.getMinutes() + " Minutes, " + start.getSeconds() + " Seconds";
},1000);
<div>Counting down from current time</div>
<span id="output"></span>

Simple JS works on every browser but safari

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.

Categories