My countdown shows the wrong hours with my current location. It shows 6 hours difference from my time zone. My time zone is Asia/Dhaka.
How do I get the correct hours? days, Minutes, and Seconds are correct. Only problem with hours.
// Got this function from thisinterestsme
function calculateChristmasCountdown() {
//Get today's date.
var now = new Date();
//Get the current month. Add a +1 because
//getMonth starts at 0 for January.
var currentMonth = (now.getMonth() + 1);
//Get the current day of the month.
var currentDay = now.getDate();
//Work out the year that the next Christmas
//day will occur on.
var nextChristmasYear = now.getFullYear();
if (currentMonth == 12 && currentDay > 25) {
//This year's Christmas Day has already passed.
nextChristmasYear = nextChristmasYear + 1;
}
var nextChristmasDate = nextChristmasYear + '-12-25T00:00:00.000Z';
var christmasDay = new Date(nextChristmasDate);
//Get the difference in seconds between the two days.
var diffSeconds = Math.floor((christmasDay.getTime() - now.getTime()) / 1000);
var days = 0;
var hours = 0;
var minutes = 0;
var seconds = 0;
//Don't calculate the time left if it is Christmas day.
if (currentMonth != 12 || (currentMonth == 12 && currentDay != 25)) {
//Convert these seconds into days, hours, minutes, seconds.
days = Math.floor(diffSeconds / (3600 * 24));
diffSeconds -= days * 3600 * 24;
hours = Math.floor(diffSeconds / 3600);
diffSeconds -= hours * 3600;
minutes = Math.floor(diffSeconds / 60);
diffSeconds -= minutes * 60;
seconds = diffSeconds;
}
//Add our counts to their corresponding HTML elements.
document.getElementById('cws_xmas_days').innerHTML = days;
document.getElementById('cws_xmas_hours').innerHTML = hours;
document.getElementById('cws_xmas_minutes').innerHTML = minutes;
document.getElementById('cws_xmas_seconds').innerHTML = seconds;
setTimeout(calculateChristmasCountdown, 1000);
}
calculateChristmasCountdown();
<span id="cws_xmas_days"></span> days
<span id="cws_xmas_hours"></span> hours
<span id="cws_xmas_minutes"></span> minutes
<span id="cws_xmas_seconds"></span> seconds
You have used the Z timezone specifier in the parsed date which means that you're counting down to 25th December using the UTC/GMT timezone. Try removing the Z to get the local equivalent.
// Got this function from thisinterestsme
function calculateChristmasCountdown() {
//Get today's date.
var now = new Date();
//Get the current month. Add a +1 because
//getMonth starts at 0 for January.
var currentMonth = (now.getMonth() + 1);
//Get the current day of the month.
var currentDay = now.getDate();
//Work out the year that the next Christmas
//day will occur on.
var nextChristmasYear = now.getFullYear();
if (currentMonth == 12 && currentDay > 25) {
//This year's Christmas Day has already passed.
nextChristmasYear = nextChristmasYear + 1;
}
var nextChristmasDate = nextChristmasYear + '-12-25T00:00:00.000';
var christmasDay = new Date(nextChristmasDate);
//Get the difference in seconds between the two days.
var diffSeconds = Math.floor((christmasDay.getTime() - now.getTime()) / 1000);
var days = 0;
var hours = 0;
var minutes = 0;
var seconds = 0;
//Don't calculate the time left if it is Christmas day.
if (currentMonth != 12 || (currentMonth == 12 && currentDay != 25)) {
//Convert these seconds into days, hours, minutes, seconds.
days = Math.floor(diffSeconds / (3600 * 24));
diffSeconds -= days * 3600 * 24;
hours = Math.floor(diffSeconds / 3600);
diffSeconds -= hours * 3600;
minutes = Math.floor(diffSeconds / 60);
diffSeconds -= minutes * 60;
seconds = diffSeconds;
}
//Add our counts to their corresponding HTML elements.
document.getElementById('cws_xmas_days').innerHTML = days;
document.getElementById('cws_xmas_hours').innerHTML = hours;
document.getElementById('cws_xmas_minutes').innerHTML = minutes;
document.getElementById('cws_xmas_seconds').innerHTML = seconds;
setTimeout(calculateChristmasCountdown, 1000);
}
calculateChristmasCountdown();
<span id="cws_xmas_days"></span> days
<span id="cws_xmas_hours"></span> hours
<span id="cws_xmas_minutes"></span> minutes
<span id="cws_xmas_seconds"></span> seconds
Related
I make a countdown timer, I need to take the number of days in a month and subtract the days that have passed (for example: 30 days of September minus 8 days - the date is today).
Now I have to enter it manually:
const end = new Date(2021, 8, 30, 13, 0,12, 12);
You can get the number of days in a month using:
const getDays = (year, month) => new Date(year, month, 0).getDate()
const days = getDays(2021, 8)
console.log(days)
Days left in current month
var currentDate = new Date();
var currentYear = currentDate.getFullYear();
var currentMonth = currentDate.getMonth();
var currentMonthLastDate = (new Date(currentYear, currentMonth, 0)).getDate();
var daysLeftInMonth = currentMonthLastDate - currentDate.getDate();
console.log(daysLeftInMonth);
A) If you won't only get the number of days in a month try this one:
<script>
function getDaysInMonth(month,year) {
var today = new Date().getDate();
// Here January is 1 based
// Day 0 is the last day in the previous month
// var monthDays = new Date(year, month, 0).getDate();
// Here January is 0 based
var monthDays = new Date(year, month+1, 0).getDate();
var remainDays = monthDays - today;
return remainDays;
}
console.log(getDaysInMonth(8, 2021));
</script>
B) If you want to get a full-timer to follow this one:
<div class="counter" style='color: green;'>
<span class='e-m-days'>0</span> Days |
<span class='e-m-hours'>8</span> Hours |
<span class='e-m-minutes'>0</span> Minutes |
<span class='e-m-seconds'>1</span> Seconds
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(function() {
function getCounterTimerData(obj) {
var days = parseInt($('.e-m-days', obj).text());
var hours = parseInt($('.e-m-hours', obj).text());
var minutes = parseInt($('.e-m-minutes', obj).text());
var seconds = parseInt($('.e-m-seconds', obj).text());
return seconds + (minutes * 60) + (hours * 3600) + (days * 3600 * 24);
}
function setCounterTimerData(s, obj) {
var days = Math.floor(s / (3600 * 24));
var hours = Math.floor((s % (60 * 60 * 24)) / (3600));
var minutes = Math.floor((s % (60 * 60)) / 60);
var seconds = Math.floor(s % 60);
console.log(days, hours, minutes, seconds);
$('.e-m-days', obj).html(days);
$('.e-m-hours', obj).html(hours);
$('.e-m-minutes', obj).html(minutes);
$('.e-m-seconds', obj).html(seconds);
}
var count = getCounterTimerData($(".counter"));
var timer = setInterval(function() {
count--;
if (count == 0) {
clearInterval(timer);
return;
}
setCounterTimerData(count, $(".counter"));
}, 1000);
});
</script>
Now you can set day, minutes, hours manually
var dt = new Date();
var month = dt.getMonth();
returns month
var year = dt.getFullYear();
var daysInMonth = new Date(year, month, 0).getDate();
// returns the diff
I'd like to create a countdown that count every hours, minutes, seconds remaining to 00:00:00 on July 13th at 12AM Miami time.
I'd like to addapt that code snippet and i struggle with calculs.
How shoud i adapt that code snippet for me to display hours, minutes, seconds instead of days, hours, minutes, seconds ?
How should i write the date for it to be 00:00:00 on July 13th at 12AM Miami time ?
What should i try next ?
Thanks.
<p id="demo"></p>
<script>
// Set the date we're counting down to
var countDownDate = new Date("Jan 5, 2022 15:37:25").getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get today's date and time
var now = new Date().getTime();
// Find the distance between now and 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 in the element with id="demo"
document.getElementById("demo").innerHTML = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
</script>
-- WayneOS code snipped modification
// Format output-string
var outputHours = (hours < 10 ? '0' + hours : hours);
var outputMinutes = (minutes < 10 ? '0' + minutes : minutes);
var outputSeconds = (seconds < 10 ? '0' + seconds : seconds);
// Display the result in the element with id="demo"
if (distance > 0)
document.getElementById("hours").innerHTML = outputHours;
document.getElementById("minutes").innerHTML = outputMinutes;
document.getElementById("seconds").innerHTML = outputSeconds;
else
document.getElementById("hours").innerHTML = "EXPIRED";
}, 1000);
```
You could use a loop to calculate the hours, minutes and seconds until distance is smaller than 1000. For it to end on Jul 13 12:00:00 use new Date("Jul 13, 2021 12:00:00 GMT-4") Here is an example.
// Set the date we're counting down to
var countDownDate = new Date("Jul 13, 2021 12:00:00 GMT-4").getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get today's date and time
var now = new Date().getTime();
// Find the distance between now and the count down date
var distance = countDownDate - now;
// Time calculations for hours, minutes and seconds
var hours = 0;
var minutes = 0;
var seconds = 0;
while (true)
if (distance >= (1000*60*60)) {
hours++;
distance -= (1000*60*60);
} else
if (distance >= (1000*60)) {
minutes++;
distance -= (1000*60);
} else
if (distance >= 1000) {
seconds++;
distance -= 1000;
} else
break;
// Format output-string
var hours = (hours < 10 ? '0' + hours : hours);
minutes = (minutes < 10 ? '0' + minutes : minutes);
seconds = (seconds < 10 ? '0' + seconds : seconds);
// Display the result in the element with id="demo"
if (distance > 0) {
document.getElementById("hours").innerHTML = hours;
document.getElementById("minutes").innerHTML = minutes;
document.getElementById("seconds").innerHTML = seconds;
} else
document.getElementById("hours").innerHTML = "EXPIRED";
}, 1000);
<div id="hours"></div>
<div id="minutes"></div>
<div id="seconds"></div>
If you have days, you can calculate the hours (days * 24 plus remaining hours). Here a little refactoring of your code. It uses setTimeout (more control and counting starts instantly) and a separate function to calculate the time units. See also.
Concerning the Miami time zone, you can create the date using timezone 'America/New_York'.
const getNextJuly13 = () => {
const now = new Date();
const miamiTime = new Date(`${
+(now.getMonth() > 6 && now.getDate() >= 13) + now.getFullYear()}/07/13 00:00`)
.toLocaleString('en', {timeZone: 'America/New_York'});
return new Date( miamiTime );
};
countDown(getNextJuly13(), document.querySelector("#demo"));
function countDown(until, writeTo) {
const distance = until - new Date();
const diffs = dateDiffCalc(distance);
const timeInfo4Demo = `\n\n=> Until ${
until.toLocaleString()} (your TZ: ${
Intl.DateTimeFormat().resolvedOptions().timeZone})\n${
JSON.stringify(diffs, null, 2)}`;
writeTo.textContent = `${diffs.totalHours}h ${
diffs.minutes}m ${diffs.seconds}s${timeInfo4Demo}`;
return distance >= 0
? setTimeout(() => countDown(until, writeTo), 1000)
: writeTo.textContent = "EXPIRED";
};
function dateDiffCalc(milliseconds) {
const secs = Math.floor(milliseconds / 1000);
const mins = Math.floor(secs / 60);
const hours = Math.floor(mins / 60);
const days = Math.floor(hours / 24);
return {
days,
hours: hours % 24,
totalHours: (days * 24) + (hours % 24),
minutes: mins % 60,
seconds: secs % 60,
};
}
<pre id="demo"></pre>
I need a little script and I am a little confused.
I want to use this plugin: http://keith-wood.name/countdown.html
Goal: Have a Countdown, that counts from now to 10:00 am - if it's 0-9:59:59 am count to 10 o'clock today if it's after 10:00:00 count to 10:00 tomorrow.
Is that understandable?
Here's what I need with javascript / jquery (this will not work, i know):
var currentDate = new Date(new Date().getTime());
var hours = currentDate.getHours();
var endTime;
if(hours >= 10){
endTime = give me next day 10:00
} else {
endTime = give me this day 10:00
}
$("#countdown").countdown({until: endTime, format: 'HMS'});
The following should work (console.log() was added for testing purposes). Beware that it will use the timezone of the browser instead of UTC time.
var currentDate = new Date(new Date().getTime());
var hours = currentDate.getHours();
var endTime = new Date(currentDate);
endTime.setMinutes(0);
endTime.setSeconds(0);
endTime.setHours(10);
if(hours >= 10){
endTime.setDate(endTime.getDate() + 1);
}
console.log(endTime);
$("#countdown").countdown({until: endTime, format: 'HMS'});
You can handle it this way.
currentDate.setHours(10,00,00);
if(hours >= 10){
endTime = currentDate.AddDays(1);
}
This is the function I use for my website:
function countDown(id, date = "Jan 5 2018") {
var int = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now an the count down date
var distance = date - 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 in the element with id="demo"
document.getElementById(id).innerHTML = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById(id).innerHTML = "00d 00h 00m 00s";
}
}, 1000);
return int;
}
In the date parameter, you need to enter your date and hour (ex. Jan 1, 2018 00:00:00) and in the id parameter the id selector (not '#myid' but only the name 'myid').
I hope this can be useful.
You can see it in action here
If you need the next day then increment the current date, then pass year, month, day and hours (static 10) to create the end date.
$(function() {
var currentDate = new Date();
var hours = currentDate.getHours();
var day;
if(hours >= 10){
day = currentDate.getDate() + 1;
} else {
day = currentDate.getDate();
}
var endTime = new Date(currentDate.getFullYear(), currentDate.getMonth(), day, 10);
$("#countdown").countdown({until: endTime, format: 'HMS'});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-countdown/2.0.2/jquery.plugin.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-countdown/2.0.2/jquery.countdown.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-countdown/2.0.2/jquery.countdown.min.css" />
<div id='countdown'></div>
I am trying to make a javascript timer that when initiated, starts counting up. The timer is just a visual reference from when a start button is clicked to when the end button is clicked.
I found a plugin online which works perfectly for counting down but I am trying to modify it to count up.
I hard coded a date way in the future. I am now trying to get the timer to start counting up to that date. This will be reset every time the start button is clicked.
This is the function I am working with. it works perfectly to count down but I cant figure out how to reverse it.
I thought it was something with how the differece was calculated but I believe it actually happens in the //calculate dates section.
Is there an easy way to reverse this math and have it count up instead?
Fiddle: http://jsfiddle.net/xzjoxehj/
var currentDate = function () {
// get client's current date
var date = new Date();
// turn date to utc
var utc = date.getTime() + (date.getTimezoneOffset() * 60000);
// set new Date object
var new_date = new Date(utc + (3600000*settings.offset))
return new_date;
};
function countdown () {
var target_date = new Date('12/31/2020 12:00:00'), // Count up to this date
current_date = currentDate(); // get fixed current date
// difference of dates
var difference = current_date - target_date;
// if difference is negative than it's pass the target date
if (difference > 0) {
// stop timer
clearInterval(interval);
if (callback && typeof callback === 'function') callback();
return;
}
// basic math variables
var _second = 1000,
_minute = _second * 60,
_hour = _minute * 60,
_day = _hour * 24;
// calculate dates
var days = Math.floor(difference / _day),
hours = Math.floor((difference % _day) / _hour),
minutes = Math.floor((difference % _hour) / _minute),
seconds = Math.floor((difference % _minute) / _second);
// fix dates so that it will show two digets
days = (String(days).length >= 2) ? days : '0' + days;
hours = (String(hours).length >= 2) ? hours : '0' + hours;
minutes = (String(minutes).length >= 2) ? minutes : '0' + minutes;
seconds = (String(seconds).length >= 2) ? seconds : '0' + seconds;
// set to DOM
//
};
// start
var interval = setInterval(countdown, 1000);
};
JSFiddle
var original_date = currentDate();
var target_date = new Date('12/31/2020 12:00:00'); // Count up to this date
var interval;
function resetCountdown() {
original_date = currentDate();
}
function stopCountdown() {
clearInterval(interval);
}
function countdown () {
var current_date = currentDate(); // get fixed current date
// difference of dates
var difference = current_date - original_date;
if (current_date >= target_date) {
// stop timer
clearInterval(interval);
if (callback && typeof callback === 'function') callback();
return;
}
// basic math variables
var _second = 1000,
_minute = _second * 60,
_hour = _minute * 60,
_day = _hour * 24;
// calculate dates
var days = Math.floor(difference / _day),
hours = Math.floor((difference % _day) / _hour),
minutes = Math.floor((difference % _hour) / _minute),
seconds = Math.floor((difference % _minute) / _second);
// fix dates so that it will show two digets
days = (String(days).length >= 2) ? days : '0' + days;
hours = (String(hours).length >= 2) ? hours : '0' + hours;
minutes = (String(minutes).length >= 2) ? minutes : '0' + minutes;
seconds = (String(seconds).length >= 2) ? seconds : '0' + seconds;
// set to DOM
//
};
// start
interval = setInterval(countdown, 1000);
};
This OP already has an answer but that has issue with timezone , so this answer.
DownVoters care to comment.
Try this. Fiddle
var TargetDate = new Date('2015', '08', '04', 11, 11, 30) // second parameter is month and it is from from 0-11
$('#spanTargetDate').text(TargetDate);
$('#spanStartDate').text(new Date());
var Sec = 0,
Min = 0,
Hour = 0,
Days = 0;
var counter = setInterval(function () {
var CurrentDate = new Date()
$('#spanCurrentDate').text(CurrentDate);
var Diff = TargetDate - CurrentDate;
if (Diff < 0) {
clearInterval(counter);
$('#timer').text('Target Time Expired. test in fiddle')
} else {
++Sec;
if (Sec == 59) {
++Min;
Sec = 0;
}
if (Min == 59) {
++Hour;
Min = 0;
}
if (Hour == 24) {
++Days;
Hour = 0;
}
if (Sec <= Diff) $('#timer').text(pad(Days) + " : " + pad(Hour) + " : " + pad(Min) + " : " + pad(Sec));
}
}, 1000);
function pad(number) {
if (number <= 9) {
number = ("0" + number).slice(-4);
}
return number;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Target Time - <span id="spanTargetDate"></span>
<br/>
<br/>Start Time - <span id="spanStartDate"></span>
<br/>
<br/>Current Time - <span id="spanCurrentDate"></span>
<br/>
<br/>Timer (DD:HH:MM:SS) - <span id="timer"></span>
<br/>
<br/>
i have the following function:
function update_comments(){
$('.comment_list_item').each(function(){
var current_comment = $(this).find('.comment_time');
var old_text = current_comment.text();
var current_time = new Date().getTime();
var timer = $(this).find('.hour_glass')
var old_time = parseFloat(timer.val());
var new_time = current_time - old_time;
var minutes=1000*60;
var hours=minutes*60;
var days=hours*24;
var new_text = '';
if(days > 0){
new_text = days+' Days ago';
}else if(hours > 0){
if(hours === 1){
new_text = hours+' Hour ago';
}else{
new_text = hours+' Hours ago';
}
}else{
if(minutes === 1){
new_text = minutes+' Minute ago';
}else{
new_text = minutes+' Minutes ago';
}
}
current_comment.text(new_text);
});
}
Where old_time is an input field with the value microtime(true);
Now after 1 minute the result is 86400000 days can anyone tell me why?
Did you read your code carefully? It includes the following lines:
var minutes=1000*60;
var hours=minutes*60;
var days=hours*24;
So yes, you are computing minutes, hours, days based on a constant (not the difference between old time and new time). Specifically, from the above it follows that
days = 1000 * 60 * 60 * 24 = 86400000
just as you observed.
The following:
var minutes = milliseconds / (1000 * 60);
var hours = minutes / 60;
var days = hours / 24;
is the more conventional approach for converting milliseconds into minutes into hours into days...
Assuming new_time is in milliseconds (very probably), You should have:
var minutes = new_time / 1000 / 60;
var hours= minutes / 60;
var days = hours / 24;
Cheers