I have an issue in displaying counter between 2 dates. I know the issue and it is that Timezone is GMT+05:30
I need to know, how to rectify that
My Solution:
var start = new Date();
var end = new Date("2017-10-03"); // This date is coming from database as <?php echo $date_end; ?>
function getClock() {
var start = new Date();
var end = new Date("<?php echo $date_end; ?>");
var diff = Math.round((end.getTime() - start.getTime()) / 1000);
var hours = Math.floor(diff / 3600);
diff -= hours * 3600
var minutes = Math.floor(diff / 60);
diff -= minutes * 60;
var seconds = diff % 60;
if(document.getElementById('countdown')){
document.getElementById('countdown').innerHTML = "<span>"
+ hours + "</span> hours <span>" + minutes + "</span> minutes <span>"
+ seconds + "</span> seconds";
}
}
setInterval('getClock()', 1000);
As start date is 02 Oct 10PM and End date is 03 Oct. So as per time calculation i shall get timer of 2 hours
but i am getting timer is 2hours+5:30 = 7:30 hours.
Please help in getting right timer.
JS Fiddle link is HERE
You can get the timezone offset from the end date after you construct it, and then use that to reassign the value.
Here is a related question.
You can use the code from that post as follows:
var end = new Date("<?php echo $date_end; ?>");
end.setTime( end.getTime() + end.getTimezoneOffset()*60*1000 );
Try something like this.
setInterval(function(){
var start = new Date();
var end = new Date("2017-10-03 00:00:00");
var diff = Math.round((end.getTime() - start.getTime()) / 1000);
var hours = Math.floor(diff / 3600);
diff -= hours * 3600
var minutes = Math.floor(diff / 60);
diff -= minutes * 60;
var seconds = diff % 60;
if(document.getElementById('countdown')){
document.getElementById('countdown').innerHTML = "<span>"
+ hours + "</span> hours <span>" + minutes + "</span> minutes <span>"
+ seconds + "</span> seconds";
}
}, 1000);
The problem is because of the way Javascript handles timezones in the Date constructor (check out the documentation for details). If, instead of passing ("2017-10-03") you pass (2017, 9, 3), it should work. To avoid these kinds of problems, it is a good idea to always work in UTC.
Make sure you pass year, month and day separately to initialize the date, so the system timezone is used, same as when you initialize your start date:
var end_str = "<?php echo $date_end; ?>";
var arr = end_str.split("-")
arr = Date.new(arr[0], arr[1]-1, arr[2]); //month is 0-indexed
Related
I wrote code in JavaScript for a counter to be output in my HTML webpage, but nothing is being printed. Where is my logic wrong?
<script>
function calCountDown(){
var temp = new Date("Dec 11, 2022"); //makes an object 'temp' with current date and time
var deadline = temp.getTime(); //stores the deadline time
temp= new Date(); //stores the object of current date and time
var currentTime = temp.getTime(); //gets the current time
var timeDifference = deadline - currentTime;
var day = Math.floor(timeDifference / (1000*60*60*24)); //calculates the difference in days from today till deadline
var hour = Math.floor((timeDifference % (1000*60*60*24))/(1000*60*60)); //calculates the difference in hours from today till deadline
var minute = Math.floor((timeDifference % (1000*60*60))/(1000*60)); //calculates the difference in minutes from today till deadline
var sec = Math.floor((timeDifference % (1000*60))/1000); //calculates the difference in seconds from today till deadline
//THIS WILL OUTPUT THE TIME EVERYTIME THIS FUNCTION IS CALLED
document.getElementById("demo").innerHTML = days + "d " + hours + "h " + minutes + "m " + seconds + "s ";
if(timeDifference < 0){
clearInterval(x);
document.getElementById("countdown").innerHTML = "ENDED !!!";
}
}
var x = setInterval(calCountDown(), 1000);
</script>
You have a couple of variables with incorrect names on this line:
document.getElementById("demo").innerHTML = days + "d " + hours + "h " + minutes + "m " + seconds + "s ";
I think it should be:
document.getElementById("demo").innerHTML = day + "d " + hour + "h " + minute + "m " + sec + "s ";
Also, you had the same value on the deadline and currentTIme variables.
I have changed it on the example below, and you can see the it outputs the time to the #demo:
function calCountDown() {
var temp = new Date("Dec 11, 2022"); //makes an object 'temp' with current date and time
var deadline = temp.getTime(); //stores the deadline time
var currentTime = new Date(); //gets the current time
var timeDifference = deadline - currentTime;
var day = Math.floor(timeDifference / (1000 * 60 * 60 * 24)); //calculates the difference in days from today till deadline
var hour = Math.floor((timeDifference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); //calculates the difference in hours from today till deadline
var minute = Math.floor((timeDifference % (1000 * 60 * 60)) / (1000 * 60)); //calculates the difference in minutes from today till deadline
var sec = Math.floor((timeDifference % (1000 * 60)) / 1000); //calculates the difference in seconds from today till deadline
//THIS WILL OUTPUT THE TIME EVERYTIME THIS FUNCTION IS CALLED
document.getElementById("demo").innerHTML = day + "d " + hour + "h " + minute + "m " + sec + "s ";
if (timeDifference < 0) {
clearInterval(x);
document.getElementById("countdown").innerHTML = "ENDED !!!";
}
}
var x = setInterval(calCountDown, 1000);
<p id="demo"></p>
Remove the () in your setInterval call:
var x = setInterval(calCountDown, 1000);
setInterval takes a function itself (or a string), you were passing it the return value from your function, which in this case is undefined.
For clarity, you were executing setInterval(undefined, 1000).
Further Opportunity to Learn
One of my most useful skills as a web developer is using the in-browser JavaScript debugger to step thru the code, set breakpoints, inspect variable values, etc.
I'd recommend you start using your JavaScript debugger to help understand what's going on in your code. Not just here, but any time you're not understanding what's going on in the code. Debuggers come with every major browser without needing any addons.
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 want to add 30 minutes and then one hour to my variable which i already have my own date
var initialDate = '10:00';
So
if (some condition){
// i add 30 minutes ->10:30
}elseif(another condition){
// i add 1hour ->11:00
}
I tried this but doesn't work
var initialDate = '10:00';
var theAdd = new Date(initialDate);
var finalDate = theAdd.setMinutes(theAdd.getMinutes() + 30);
If I understand you correctly, the following will help you.
You need to add momentjs dependency via script tag and you can Parse, validate, manipulate, and display dates in JavaScript.
You can find more documentation regarding this in momentjs website
console.log(moment.utc('10:00','hh:mm').add(1,'hour').format('hh:mm'));
console.log(moment.utc('10:00','hh:mm').add(30,'minutes').format('hh:mm'));
<script src="https://momentjs.com/downloads/moment-with-locales.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
var theAdd = new Date();
// Set Hours, minutes, secons and miliseconds
theAdd.setHours(10, 00, 00, 000);
if (some condition) {
// add 30 minutes --> 10:30
theAdd.setMinutes(theAdd.getMinutes() + 30);
}
elseif (some condition) {
// add 1 hour --> 11:00
theAdd.setHours(theAdd.getHours() + 1);
}
Then you print the var theAdd to obtain the date and time.
To obtain just the time:
theAdd.getHours() + ":" + theAdd.getMinutes();
This should do the job. Dates need a year and month in their constructor, and you have to specify larger units of time if you specify and smaller ones, so it needs a day as well. Also, you have to pass in the hours and minutes separately. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date.
var initialDate = '10:00';
var theAdd = new Date(1900,0,1,initialDate.split(":")[0],initialDate.split(":")[1]);
if(30 min condition){
theAdd.setMinutes(theAdd.getMinutes() + 30);
} else if (1 hour condition){
theAdd.setHours(theAdd.getHours() + 1);
}
console.log(theAdd.getHours()+":"+theAdd.getMinutes());
Here is a javascript function that will add minutes to hh:mm time string.
function addMinutes(timeString, addMinutes) {
if (!timeString.match(/^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/))
return null;
var timeSplit = timeString.split(':');
var hours = parseInt(timeSplit[0]);
var minutes = parseInt(timeSplit[1]) + parseInt(addMinutes);
hours += Math.floor(minutes / 60);
while (hours >= 24) {
hours -= 24;
}
minutes = minutes % 60;
return ('0' + hours).slice(-2) + ':' + ('0' +minutes).slice(-2);
}
So I found this code on this site but there's one thing I want to change about it, but I can't seem to figure it out so I need some help. What I want to do is to remove the year in the date, so that the countdown corresponds the year that it is.
<script>
var end = new Date('04/19/2017 10:1 AM');
var _second = 1000;
var _minute = _second * 60;
var _hour = _minute * 60;
var _day = _hour * 24;
var timer;
function showRemaining() {
var now = new Date();
var distance = end - now;
if (distance < 0) {
clearInterval(timer);
document.getElementById('countdown').innerHTML = 'EXPIRED!';
return;
}
var days = Math.floor(distance / _day);
var hours = Math.floor((distance % _day) / _hour);
var minutes = Math.floor((distance % _hour) / _minute);
var seconds = Math.floor((distance % _minute) / _second);
document.getElementById('countdown').innerHTML = days + 'days ';
document.getElementById('countdown').innerHTML += hours + 'hrs ';
document.getElementById('countdown').innerHTML += minutes + 'mins ';
document.getElementById('countdown').innerHTML += seconds + 'secs';
}
timer = setInterval(showRemaining, 1000);
</script>
<div id="countdown"></div>
Credit for the code goes out to this guy
All you have to do is to create a new Date instance without any parameters. This will give you a Date object with the current datetime. But this is very insecure because your information will come from the browser (the client's machine). You should generate this on the server.
Whatever, if you don't know how to create that instance in Javascript, here you go:
var currentDatetime = new Date();
var currentYear = currentDatetime.getFullYear();
And then you can do something like this:
var end = new Date('04/19/' + currentYear + ' 10:1 AM');
You can explore what that Date class can do here: https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Date
You should not parse strings with the Date constructor, they should be manually parsed with either a small function or library.
Assuming you have a date object, the year can be set using setFullYear, so:
// Create a date for 25 March, 2006
var d = new Date(2006, 2, 25);
console.log(d.toString());
// Set to current year
d.setFullYear(new Date().getFullYear());
console.log(d.toString());
If the date doesn't exist in the new year, e.g. if the starting date was 29 February 2016, then it rolls over to the next day, 1 March 2017.
If you know the date parts, you can go the other way and create a date and set the month and date, e.g.
// Create a date for 30 June in the current year
var d = new Date();
d.setMonth(5,30);
// Zero the time component
d.setHours(0,0,0,0);
console.log(d.toString());
What I'd like to accomplish is a countdown that updates live... like this:
6 Days (just the days)
12 Hours (just hours within 1 day)
59 Minutes (just minutes within 1 hour)
59 Seconds (just seconds within 1 minute)
Best way to accomplish this?
You can find a working example at http://jsfiddle.net/gaby/QH6X8/79/
var end = new Date('15 Dec 2010');
var _second = 1000;
var _minute = _second * 60;
var _hour = _minute * 60;
var _day = _hour *24
var timer;
function showRemaining()
{
var now = new Date();
var distance = end - now;
if (distance < 0 ) {
// handle expiry here..
clearInterval( timer ); // stop the timer from continuing ..
alert('Expired'); // alert a message that the timer has expired..
}
var days = Math.floor(distance / _day);
var hours = Math.floor( (distance % _day ) / _hour );
var minutes = Math.floor( (distance % _hour) / _minute );
var seconds = Math.floor( (distance % _minute) / _second );
var countdownElement = document.getElementById('countdown');
countdownElement.innerHTML = 'Days: ' + days + '<br />';
countdownElement.innerHTML += 'Hours: ' + hours+ '<br />';
countdownElement.innerHTML += 'Minutes: ' + minutes+ '<br />';
countdownElement.innerHTML += 'Seconds: ' + seconds+ '<br />';
}
timer = setInterval(showRemaining, 1000);
jQuery Countdown plugin
here you can generate countdown timer if you like - just press generate and copy paste the results into .html file
http://www.ricocheting.com/code/javascript/html-generator/countdown-timer
Notable mention: http://www.littlewebthings.com/projects/countdown/
(probable irrelevant since you mentioned that you don't want to use a plugin)
The problem with the above accepted approach is that there will be issues here related to timezone differences and daylight saving time. See this question asked by me Javascript Countdown and Timezone and Daylight Saving Time Issues
jCounter offers control on what format you want your countdown to display among other control settings and methods.