I am trying to create a javascript countdown which displays the hours and minutes, counting down to midday each day. When midday is reached I would like the timer to reset and start counting down to midday again (obviously to countdown to the following day).
I have the code below, however I just can't get it to work properly, the code works fine after midday however once midnight is reached the count is incorrect.
Here is my code:
function ShowTimes() {
var now = new Date();
var hrtime = now.getHours()
var hrs = 23 - hrtime + 12;
var mins = 59-now.getMinutes();
var secs = 59-now.getSeconds();
var str = '';
str += hrs+' hours '+mins+' minutes';
document.getElementById('countdown').innerHTML = str;
}
var _cntDown;
function StopTimes() {
clearInterval(_cntDown);
}
Any help is much appreciated! Thanks in advance.
Do you live somewhere that moves clocks forwards/backwards in spring/autumn?
If so, you'll have two days in the year where your hour and minute logic would fail.
Here's a way that works even when the clocks change:
var now = new Date();
var midday = new Date(now.getFullYear(), now.getMonth(), now.getDate() + (now.getHours() >= 12 ? 1 : 0), 12);
var millisToMidday = midday.getTime() - now.getTime();
var hours = Math.floor((millisToMidday / (60 * 60 * 1000)))
var minutes = Math.floor((millisToMidday / (60 * 1000))) % 60;
var seconds = Math.floor((millisToMidday / (1000))) % 60;
Change the logic for Hrs calculation as below :
if(hrtime>12)
hrtime=23- hrtime+ 12;
else
hrtime= 12-hrtime;
Related
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
I was trying to implement count down timer for my web site. I want to give two static dates to and get the count down running. I found an example that uses one hard code date and the other date is taken as new Date() . but when I change that new Date() to Hard Code values count down timer stopped . How to fix this issue .
Original Example I found in jsfiddle.net
My modified Example in jsfiddle.net
the only difference in those examples is i changed var date1 = new Date(); to var date1 = new Date("2017/07/22 20:30:00");
The dates that you provided will never change since you are continually calling the same function each interval (i.e. the difference between date1 and date2 will never change).
If you want a countdown, you'll need to use some relatively changing date similar to the original example you provided or retain an offset (i.e. store when you started the process and continually use an offset for your calculations) as seen below:
// Store a relative date to track passing time
var started = new Date();
showDiff();
function showDiff() {
// Keep track of the time that has elapsed
var offset = new Date() - started;
// Store your dates
var date1 = new Date("2017/07/22 20:30:00") - offset;
var date2 = new Date("2015/07/30 21:59:00");
// Calculate the differences
var diff = Math.abs(Math.floor((date2 - date1) / 1000));
var days = Math.floor(diff / (24 * 60 * 60));
var daysLeft = diff - days * 24 * 60 * 60;
var hours = Math.floor(daysLeft / (60 * 60));
var hoursLeft = daysLeft - hours * 60 * 60;
var minutes = Math.floor(hoursLeft / (60));
var minutesLeft = hoursLeft - minutes * 60;
var seconds = Math.floor(minutesLeft / 60);
var secondsLeft = minutesLeft - seconds * 60;
// Output
document.getElementById("showTime").innerHTML = "You have " + days + " days " + hours + " hours " + minutes + " minutes and " + secondsLeft + " seconds before death.";
setTimeout(showDiff, 1000);
}
<div id='showTime'></div>
I have start date time and end time,i need to split how many days , hours ,minutes in the two dates
for example ,
startdatetime = "09-06-2017 10:30"
enddatetime = "10-06-2017 11:45"
i need this result : 1 day 1 hour and 15 minutes
I try this one
var t = end - start;
var z = parseInt(t / 1000 / 60);
var time = display(z);
function display(a)
{
console.log(a);
var hours = Math.trunc(a/60);
var minutes = a % 60;
var one_day=1000*60*60*24
var days = Math.ceil(a/one_day)
var time = [hours,minutes,days];
return time;
}
i get the following 1day 24 hours and 15 minutes , can anyone help me , if its new logic means i will change into it,thanks in advance
Using momentjs, you can :
Parse your input string using moment(String, String)
Parse your input string using moment.utc
Get difference using diff() function
Create a duration from the difference value
Use duration days(), hours(), minutes() to get your result
Here a live sample:
var startdatetime = "2017-06-09T07:00:01.000Z";
var enddatetime = "2017-06-10T09:00:00.000Z";
// Parse input
var mStart = moment.utc(startdatetime);
var mEnd = moment.utc(enddatetime);
// Calculate difference and create duration
var dur = moment.duration( mEnd.diff(mStart) );
// Show the result
console.log(dur.days() + ' days ' + dur.hours() + ' hour ' + dur.minutes() + ' minutes');
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
If you want you can use moment-duration-format plug-in to get the same result using format() method on duration. Here a working sample:
var startdatetime = "2017-06-09T07:00:01.000Z";
var enddatetime = "2017-06-10T09:00:00.000Z";
// Parse input
var mStart = moment.utc(startdatetime);
var mEnd = moment.utc(enddatetime);
// Calculate difference and create duration
var dur = moment.duration( mEnd.diff(mStart) );
// Show the result
console.log(dur.format('d [day] h [hour] m [minutes]'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-duration-format/1.3.0/moment-duration-format.min.js"></script>
Well, if you look at documentation for javascript Date objects, there is a getTime() method . You can also use the valueOf() method. They both return the number of milliseconds representing your Date object.
You can simply call that on both Date objects and then find the difference. Once you have the difference you can find the amount of secs, mins , hrs, days, etc. Here is an example:
var start = new Date(*some date*);
var end = new Date(*some date*);
var dif = end.valueOf() - start.valueOf();
if (dif >= 0) {
var secs = Math.floor(dif / 1000 % 60);
var mins = Math.floor(dif / 1000 / 60 % 60);
var hrs = Math.floor(dif / 1000 / 60 / 60 % 24);
var days =
Math.floor(dif / 1000 / 60 / 60 / 24 % 365);
var yrs =
Math.floor(dif / 1000 / 60 / 60 / 24 / 365);
Try the following:
var t = end - start;
var z = parseInt(t / 1000 / 60);
var time = display(z);
function display(minutes)
{
var hours = (minutes / 60 | 0) % 24;
var minutes = (minutes | 0) % 60;
var days = minutes / 60 / 24 | 0;
return [hours, minutes, days];
}
Note that in javascript, doing x | 0 is the same as Math.floor(x).
It looks to me like your calculation for hours still has the days in it. Once you have established the days, just subtract those out when you calculate the hours.
var start = new Date("June 09, 2017 10:30:00");
var end = new Date("June 10, 2017 11:45:00");
var t = end - start;
var z = parseInt(t / 1000 / 60);
var time = display(z);
console.log(time);
function display(a)
{
var minutes = a % 60;
var one_day=1000*60*60*24
var days = Math.ceil(a/one_day)
var hours = Math.trunc((a-(days*1440))/60);
var time = [hours,minutes,days];
return time;
}
Having said that, I highly recommend moment.js to handle this type of thing, if you can.
var startDateTime = 1497029400000;
var endDateTime = 1497120300000;
var timeDifference = endDateTime - startDateTime
// with the given dates, days equals 1.0520833333333333
// we want to extract the trailing decimal values using modulus to get the other times
function getTimeDifference(timeDifference) {
var days = timeDifference/1000/60/60/24
days >= 1
? var dayCount = Math.trunc(days); // store the day count
: var dayCount = 0; // it is less than one day
// get the remaining hours
var hours = (days % 1) * 24;
var hoursCount = Math.trunc((days % 1) * 24);
// get the remaining minutes
var minutesCount = Math.ceil((hours % 1) * 60);
}
Working on a javascript-canvas based clock (classic analog clock view), also displaying the current date below the clock.
I already have this code to get the current time in javascript:
// get current time
var date = new Date();
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();
hours = hours > 12 ? hours - 12 : hours;
var hour = hours + minutes / 60;
var minute = minutes + seconds / 60;
Works great, except that I don't know how to get the number in seconds until the end of the day, so I could run an ajax request at 00:00h to update the current date.
The question is, how to get easily the number in seconds until end of the day in javascript?
I plan to start a setTimeout()-function after the clock loaded with the number of seconds left, to update the date when needed.
I'm assuming the date you want to change is not from these values. You need to change it in some place not directly related to this clock?
I would suggest to add a function to check if the day has changed and include it when the clock is refreshed.
In any case, getting the seconds to the end of the day should be something like
var secondsUntilEndOfDate = ( (24*60*60) - ( (hours*60*60) + (minutes*60) + seconds ) );
Javascript:
var d = new Date();
var h = d.getHours();
var m = d.getMinutes();
var s = d.getSeconds();
var secondsUntilEndOfDate = (24*60*60) - (h*60*60) - (m*60) - s;
For GMT+0 it would be
const secondUntilEndOfTheDay = 86400 - Math.floor(new Date() / 1000) % 86400;
I am trying to get the current time difference in hours and minutes between now and 12pm (midday). If it is past 12pm on the current day it must then count down the hours onto the next day.
I have looked around here for a while now and have found many examples on getting date differences but and am unable to get a working solution for time so have been playing around with writing my own. However I am unable to getTime(); to get hours and minutes from the millisecond timestamp on my new dates and am unsure why exactly. Here is my code:
dateone = new Date();
datetwo = new Date();
datetwo = datetwo.setHours(12);
dateone = dateone.getTime();
datetwo = datetwo.getTime();
if(dateone > datetwo) {
var seconds = dateone - datetwo;
} else {
var seconds = datetwo - dateone;
}
var d = seconds;
var minutes=(d/(1000*60))%60;
var hours=(d/(1000*60*60))%24;
var minutesround=Math.floor(minutes);
var hoursround=Math.round(hours);
var endtime = 12;
alert(hours);
alert(minutes);
If anyone is able to spot a better way of doing this, or can suggest anything it would be greatly appreciated!
Thanks,
Simon
Try
var d = new Date(), midDay = new Date();
midDay.setHours(12);
midDay.setMinutes(0);
midDay.setSeconds(0);
if(d > midDay) {
midDay.setDate(midDay.getDate() + 1)
}
var diff = (midDay.getTime() - d.getTime()) / 1000;
var hrs = parseInt(diff / 3600);
diff = diff % 3600;
var minutes = parseInt(diff / 60);
console.log(hrs, minutes)
Demo: Fiddle