I have found a code but i dont know to add timezone . i want to detect the timer from the timezone of the other country like denmark/copenhagen. thank you. this is my code.
<script type="text/javascript">
ElapsedTimeLogger = function(dateElementId, elapsedElementId, hiden, interval) {
var container = $(elapsedElementId);
var time = parseDate($(dateElementId).val());
var interval = interval;
var timer;
function parseDate(dateString) {
var date = new Date(dateString);
return date.getTime();
}
function update() {
var systemTime = new Date().getTime();
elapsedTime = systemTime - time;
container.html(prettyPrintTime(Math.floor(elapsedTime / 1000)));
$(hiden).val(prettyPrintTime(Math.floor(elapsedTime / 1000)));
}
function prettyPrintTime(numSeconds) {
var hours = Math.floor(numSeconds / 3600);
var minutes = Math.floor((numSeconds - (hours * 3600)) / 60);
var seconds = numSeconds - (hours * 3600) - (minutes * 60);
if (hours < 10) hours = "0" + hours;
if (minutes < 10) minutes = "0" + minutes;
if (seconds < 10) seconds = "0" + seconds;
var time = hours + ":" + minutes + ":" + seconds;
return time;
}
this.start = function() {
timer = setInterval(function() {update()}, interval * 1000);
}
this.stop = function() {
clearTimeout(timer);
}
}
$(document).ready(function () {
var timeLogger = new ElapsedTimeLogger("#date", "#elapsed","#stoppedid", 1);
timeLogger.start();
$("#confirm").click(function() { //Stop timer upon clicking the Confirm Button
timeLogger.stop();
});
});
</script>
thank you. i dont know javascript. i know php only. i tried to put
before the code is running. i already save a time from europe/copenhagen. but when the timer is running. it says 6:00:01 abd counting.. but i want to run like this 0:00:01 and counting. and my idea the time from europe and time in my country is 6 hours. i want to run the time from europe not my country. because i save the time from europe using php. see bellow the code for save the time.
date_default_timezone_set("Europe/Copenhagen");
but wont work. i didnt found the solution
Analyzing this code, I rewrote the needed HTML to see what the code do. It's simply creates a counter in format hh:mm:ss and shows on screen, this counter show the time passed since the date informed.
to add the user timezone to reflect in your timer, you just need to recalculate the seconds inside the prettyPrintTime(numSeconds) function before use it to get hours, minutes and seconds.
function prettyPrintTime(numSeconds) {
var tzOffset = new Date().getTimezoneOffset(); // get the timezone in minutes
tzOffset = tzOffset * 60; // convert minutes to seconds
numSeconds -= tzOffset; // recalculate the time using timezone
var hours = Math.floor(numSeconds / 3600);
var minutes = Math.floor((numSeconds - (hours * 3600)) / 60);
var seconds = numSeconds - (hours * 3600) - (minutes * 60);
if (hours < 10) hours = "0" + hours;
if (minutes < 10) minutes = "0" + minutes;
if (seconds < 10) seconds = "0" + seconds;
var time = hours + ":" + minutes + ":" + seconds;
return time;
}
Take a look at the working code:
https://jsfiddle.net/4c6xdcpr/
function getClientTimeZone() {
var offset = new Date().getTimezoneOffset(),
o = Math.abs(offset);
return (offset < 0 ? "+" : "-") + ("00" + Math.floor(o / 60)).slice(-2) + ":" + ("00" + (o % 60)).slice(-2);
}
// Display Output
alert(getClientTimeZone());
Related
I am trying to create countdown timer between 2 dates but the time is lagging behind after a while.
My PHP backend returns the difference between current time and X time in the future, for example current time and 2 hours in advance. This difference is passed to my HTML frontent in a .countdown class in the following format 03:20:15 which I use a javascript function to countdown the difference. Here is my function:
$(".countdown").each(function() {
var $e = $(this);
var interval = setInterval(function() {
var timer2 = $e.html();
var timer = timer2.split(':');
var hours = parseInt(timer[0], 10);
var minutes = parseInt(timer[1], 10);
var seconds = parseInt(timer[2], 10);
--seconds;
minutes = (seconds < 0) ? --minutes : minutes;
hours = (minutes < 0) ? --hours : hours;
if(hours < 0) {
clearInterval(interval);
window.location.reload();
} else {
seconds = (seconds < 0) ? 59 : seconds;
seconds = (seconds < 10) ? '0' + seconds : seconds;
minutes = (minutes < 0) ? 59 : minutes;
minutes = (minutes < 10) ? '0' + minutes : minutes;
hours = (hours < 10) ? '0' + hours : hours;
$e.html(hours + ':' + minutes + ':' + seconds);
}
}, 1000);
});
The code works as expected but after a few minutes, lets say 2-3 minutes, if you refresh the page or open it in a new window you will see that the countdown timer was lagging behind by seconds/minutes. Does someone know what Im doing wrong?
You should compute the difference between (new Date()) and the target date. Use that difference and format new HTML string instead of parsing it to a hour, minutes, seconds value for decrementing.
details
The setInterval api specs suggest that delays due to CPU load, other tasks, etc, are to be expected.
https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#timers
Your handler is called at approximately equal intervals while you consider them to be exact. At first iteration the actual time may differ from a planed time by some small amount (let say 4ms). Yet you are changing your counter by 1000 ms. As many more iterations passed this difference accumulates and become noticeable. A few minutes is enough to make this happens.
If you, on the other hand, pre-compute the target date-time value and will use the difference between current time and the target time your code will not be sensible to api inexactness.
$(".countdown").each(function () {
var $e = $(this);
const totalSeconds = (dt) => Math.floor(dt.valueOf() / 1000);
const f1 = (timer2) => {
var timer = timer2.split(':');
var tdt = new Date().setHours(
parseInt(timer[0]) + tdt.getHours(),
parseInt(timer[1]) + tdt.getMinutes(),
parseInt(timer[2]) + tdt.getSeconds());
return totalSeconds(tdt);
};
const targetTime = f1($e.html());
setInterval(function () {
var timeSpan = targetTime - totalSeconds(new Date());
if (timeSpan < 0) {
window.location.reload();
} else {
var seconds = timeSpan % 60;
var totalMinutes = Math.floor(timeSpan / 60);
var minutes = totalMinutes % 60;
var hours = Math.floor(totalMinutes / 60);
$e.html(hours + ':' + minutes + ':' + seconds);;
}
}, 1000);
});
see also:
https://jsfiddle.net/8dygbo9a/1/
I have created an online examination system and I have put a countdown timer in online examination system. Below is my javascript code. Plz check
<h2><p style="float: right" id="countdown"></p></h2>
<script>
$(document).ready(function () {
$examination_test_id = $("#examination_test_id").val();
$time_limit = $("#time_limit").val();
var d = new Date($time_limit); //14-August-2016 01:20:00
var hours = d.getHours(); //01
var minute = d.getMinutes(); //20
var minutes = hours * 60 + minute;
var seconds = 60 * minutes; //00
console.log(seconds);
if (typeof (Storage) !== "undefined") { //checks if localStorage is enabled
if (sessionStorage.seconds) { //checks if seconds are saved to localstorage
seconds = sessionStorage.seconds;
}
}
function secondPassed() {
var minutes = parseInt((seconds) / 60);
var hours = parseInt(minutes / 60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
if (typeof (Storage) !== "undefined") {
sessionStorage.setItem("seconds", seconds);
}
document.getElementById('countdown').innerHTML = hours + ":" + minutes + ":" + remainingSeconds;
if (seconds == 0) {
clearInterval(myVar);
document.getElementById('countdown').innerHTML = alert('Timeout');
window.location.href = base_url + "student/Examinations/check_answer/" + $examination_test_id;
if (typeof (Storage) !== "undefined") {
sessionStorage.removeItem("seconds");
}
} else {
seconds--;
}
}
var myVar = setInterval(secondPassed, 1000);
});
});
</script>
MY Question: coundown timer should start at 01:20:00 ,but in my case, countdown timer starts at 01:80:00 , why? please check my javascript code
var minutes = hours * 60 + minute;
One hour and twenty minutes is 80 minutes in total. You should change that line to just have var minutes = minute;
In minutes, you are taking the total,
var minutes = hours * 60 + minute;
80= 1*60 + 20
in less than 5 seconds i just found an answer: Javascript return number of days,hours,minutes,seconds between two dates
or JavaScript seconds to time string with format hh:mm:ss
So please just search a little bit before posting this kind of question
I have been looking for a count down timer on google and can't seem to find one.
I was just wondering if anyone would be able to help.
I got given one but it displays the wrong times.
I want it to display days, hours, minutes and seconds left.
heres what I need the timer on
http://pastebin.com/fQjyRFXw
It already has the timer code there but it's all wrong, any help would be great, thank you
If it's helps here's a snippet of the Java code
var count = <?= $time['a_time'] ?>;
var counter = setInterval(timer, 1000); //1000 will* run it every 1 second
function timer() {
count = count - 1;
if(count == -1) {
clearInterval(counter);
return;
}
var seconds = count % 60;
var minutes = Math.floor(count / 60);
var hours = Math.floor(minutes / 60);
minutes %= 60;
hours %= 60;
document.getElementById("clock").innerHTML = hours + "hours " + minutes + "minutes and " + seconds + " seconds left";
}
Ok I see your problem. The a_time stored in database is an Unix timestamp, thus when you are counting down, you need to know how long is between now and a_time instead of only a_time.
Try this:
var count = <?= $time['a_time'] ?>;
var now = Math.floor(new Date().getTime() / 1000);
count = count - now;
var counter = setInterval(timer, 1000); //1000 will* run it every 1 second
function timer() {
count = count - 1;
if(count == -1) {
clearInterval(counter);
return;
}
var seconds = count % 60;
var minutes = Math.floor(count / 60);
var hours = Math.floor(minutes / 60);
var days = Math.floor(hours / 24);
minutes %= 60;
hours %= 24;
document.getElementById("clock").innerHTML = days + "days " + hours + "hours " + minutes + "minutes and " + seconds + " seconds left";
}
Why not use one of the man examples on codepen such as this beautiful one
http://codepen.io/anon/pen/VeLWdz ?
(function (e) {
e.fn.countdown = function (t, n) {
function i() {
eventDate = Date.parse(r.date) / 1e3;
currentDate = Math.floor(e.now() / 1e3);
if (eventDate <= currentDate) {
n.call(this);
clearInterval(interval)
}
seconds = eventDate - currentDate;
days = Math.floor(seconds / 86400);
seconds -= days * 60 * 60 * 24;
hours = Math.floor(seconds / 3600);
seconds -= hours * 60 * 60;
minutes = Math.floor(seconds / 60);
seconds -= minutes * 60;
days == 1 ? thisEl.find(".timeRefDays").text("day") : thisEl.find(".timeRefDays").text("days");
hours == 1 ? thisEl.find(".timeRefHours").text("hour") : thisEl.find(".timeRefHours").text("hours");
minutes == 1 ? thisEl.find(".timeRefMinutes").text("minute") : thisEl.find(".timeRefMinutes").text("minutes");
seconds == 1 ? thisEl.find(".timeRefSeconds").text("second") : thisEl.find(".timeRefSeconds").text("seconds");
if (r["format"] == "on") {
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
}
if (!isNaN(eventDate)) {
thisEl.find(".days").text(days);
thisEl.find(".hours").text(hours);
thisEl.find(".minutes").text(minutes);
thisEl.find(".seconds").text(seconds)
} else {
alert("Invalid date. Example: 30 Tuesday 2013 15:50:00");
clearInterval(interval)
}
}
var thisEl = e(this);
var r = {
date: null,
format: null
};
t && e.extend(r, t);
i();
interval = setInterval(i, 1e3)
}
})(jQuery);
$(document).ready(function () {
function e() {
var e = new Date;
e.setDate(e.getDate() + 60);
dd = e.getDate();
mm = e.getMonth() + 1;
y = e.getFullYear();
futureFormattedDate = mm + "/" + dd + "/" + y;
return futureFormattedDate
}
$("#countdown").countdown({
date: "1 April 2017 09:00:00", // Change this to your desired date to countdown to
format: "on"
});
});
I am implementing an analogue and digital watch with JS. Got it working with a couple of tutorials but how can I stop the clock and change the hour? Here is the code for digital one:
function updateClock() {
var currentTime = new Date();
var gtmStatus = 'AM';
var hours = currentTime.getHours();
if (hours > 12){
hours = hours-12;
gtmStatus = 'PM';
}
var minutes = currentTime.getMinutes();
var seconds = currentTime.getSeconds();
var degree_seconds = -90 + (seconds * 6);
var degree_minute = -90 + (minutes * 6);
var degree_hour = -90 + (hours * 30);
degree_hour = degree_hour + (0.5 * minutes);
$('#time').html(hours + ':' + minutes + ':' + seconds + ' ' + gtmStatus);
setInterval(updateClock, 1000);
updateClock();
}
setInterval(...) returns a handle/identifier that can be given to clearInterval(handle).
In other words, if you want to pause your clock, you need to call clearInterval(...) with the previously obtained handle from the last call of setInterval(...). Then, you can start your clock calling setInterval(...) again.
function getThatThereTime () {
return $('#time').val();
}
Let me first say I do not have a deep understanding of javascript but I know how to work my way around enough to write small scripts for pages. A client of mine needs me to do the following for a website:
Find the user's local time on their computer.
Take that local time and subtract it from 6pm.
Display that time in a countdown or just a statement letting the user know how much time is left for same day shipping.
After 6pm the time resets or disappears until the next business day.
So far I've been able to create the logic for getting the time from the local computer. I thought I'd be able to use datejs but it does not calculate hours in a day.
Here is the current code I have:
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
var suffix = "AM";
if (hours >= 12)
{
suffix = "PM";
hours = hours - 12;
}
var suffix = "AM";
if (hours >= 12)
{
suffix = "PM";
hours = hours - 12;
}
if (hours == 0)
{
hours = 12;
}
if (minutes < 10)
minutes = "0" + minutes;
document.write("<b>" + hours + ":" + minutes + " " + suffix + "</b>");
How about this:
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
var suffix = "AM";
if (hours >= 12) {
suffix = "PM";
hours = hours - 12;
}
if (minutes < 10)
minutes = "0" + minutes
if (suffix == "PM" && hours >= 6)
{
document.write("You're too late for next day shipping!");
}
else
{
var hoursLeft = 5 - hours;
var minsLeft = 60 - minutes;
document.write("<b> You've got " + hoursLeft + " hours and " + minsLeft + " minutes left to qualify for next day shipping! </b>")
}
if this site would let me comment on other people's answers I'd give the credit for this to Giovanni, but since I can't yet comment on other people's work, here's what needs to change.
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
var suffix = "AM";
if (minutes < 10)
minutes = "0" + minutes
if (hours >= 18)
{
document.write("You're too late for next day shipping!");
}
else
{
var hoursLeft = 17 - hours;
var minsLeft = 60 - minutes;
if(minsLeft==60){
minsLeft=0;
hoursLeft++;
}
document.write("<b> You've got " + hoursLeft + " and " + minsLeft + " minutes left to qualify for next day shipping! </b>")
}
The reason for this is that people who are ordering at 5AM might see think that they have to submit within the next hour for their shipping to be next day when in fact they have the next 13 hours.
EDIT: saw your timezone concern and here is a post that might interest you.
EDIT 2: posted the wrong link. The correct one should be up now, though it might be a bit of a dated answer.
Something similar I solved also yesterday, so this is easy. Here is the javascript code:
function start_onload(last_hour){
var timeout_message = document.getElementById('timeout_message');
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
var seconds = currentTime.getSeconds();
var expire_time = 0; // in seconds
if (hours<last_hour) {
expire_time += (last_hour-hours-1)*3600;
expire_time += (59-minutes)*60;
expire_time += (59-seconds);
}
else {
timeout_message.innerHTML = 'It\'s after '+last_hour+' o\'clock!';
return;
}
var expire_time = currentTime.getTime() + 1000*expire_time;
//console.log(expire_time, hours, minutes, seconds, expire_time);
function countdown_session_timeout() {
var current_time = new Date().getTime();
var remaining = Math.floor((expire_time - current_time)/1000);
if (remaining>0) {
hours = Math.floor(remaining/3600);
minutes = Math.floor((remaining - hours*3600)/60);
seconds = remaining%60;
timeout_message.innerHTML = 'Countdown will stop in '+ hours + ' hours ' + minutes + ' min. ' + seconds + ' sec.';
setTimeout(countdown_session_timeout, 1000);
} else {
timeout_message.innerHTML = 'Time is up!';
}
}
countdown_session_timeout();
}
Full script # pastebin.com is here.
This is a simple countdown timer starting at 30 seconds from when the function is run and ending at 0. After reaching 0 it automatically reset the counter. It goes again to 30 second and this process is continued in a loop
window.onload = function() { startCountDown(30,
1000, myFunction); }
function startCountDown(i, p, f) { var pause = p; var fn = f;
var countDownObj = document.getElementById("countDown");
countDownObj.count = function(i) {
//write out count
countDownObj.innerHTML = i;
if (i == 0) {
//execute function
//fn();
startCountDown(30, 1000, myFunction); //stop
return; } setTimeout(function() {
// repeat
countDownObj.count(i - 1);
},
pause
); } //set it going countDownObj.count(i); }
function myFunction(){};
</script>