I need to show the server time on a clock. Below is the code i currently have. I get the server time with Ajax call. The problem is that if the user changes it's local/computer clock it will also update the script's clock which is not ok - it should continue without changing and i'm stuck. I've tried passing the serverTime within the setTimeout so it get's used every time as a reference but no luck with that.
var serverTime = 1490856278000;
var localTime = +Date.now();
var timeDiff = serverTime - localTime;
var realTime;
var date;
var hours;
var minutes;
var seconds;
setInterval(function () {
realTime = +Date.now() + timeDiff;
date = new Date(realTime);
hours = date.getHours();
minutes = date.getMinutes();
seconds = date.getSeconds();
document.getElementById('clock').innerHTML = hours + ':' + minutes + ':' + seconds;
}, 1000);
<div id="clock"></div>
You should be able to compare each realTime with the last one in your setInterval. If the difference is far from the 1000ms that it is supposed to be, do an ajax call to query the server time again and renew the timeDiff.
Also you can try to use performance.now instead of Date.now. The higher resolution is unnecessary and possibly expensive, but MDN states that
unlike Date.now(), the values returned by Performance.now() always increase at a constant rate, independent of the system clock (which might be adjusted manually or skewed by software like NTP)
Using How to create an accurate timer in javascript? and Bergi's answer I prepared an another way. I think you don't have to use the local time at all:
var serverTime = 1490856278000;
var expected = serverTime;
var date;
var hours;
var minutes;
var seconds;
var now = performance.now();
var then = now;
var dt = 0;
var nextInterval = interval = 1000; // ms
setTimeout(step, interval);
function step() {
then = now;
now = performance.now();
dt = now - then - nextInterval; // the drift
nextInterval = interval - dt;
serverTime += interval;
date = new Date(serverTime);
hours = date.getUTCHours();
minutes = date.getUTCMinutes();
seconds = date.getUTCSeconds();
document.getElementById('clock').innerHTML = hours + ':' + minutes + ':' + seconds;
console.log(nextInterval, dt); //Click away to another tab and check the logs after a while
now = performance.now();
setTimeout(step, Math.max(0, nextInterval)); // take into account drift
}
<div id="clock"></div>
The time will change because Date.now(); is getting it's time from the Client machine. There are no AJAX calls in your script.
More Updated with AM & PM
var serverTime = 1490856278000;
var expected = serverTime;
var date;
var h;
var m;
var s;
var now = performance.now();
var then = now;
var dt = 0;
var nextInterval = (interval = 1000);
setTimeout(step, interval);
function step() {
then = now;
now = performance.now();
dt = now - then - nextInterval;
nextInterval = interval - dt;
serverTime += interval;
date = new Date(serverTime);
h = date.getHours();
m = date.getMinutes();
s = date.getSeconds();
var session = "AM";
if (h == 0) {
h = 12;
}
if (h > 12) {
h = h - 12;
session = "PM";
}
h = h < 10 ? "0" + h : h;
m = m < 10 ? "0" + m : m;
s = s < 10 ? "0" + s : s;
var time = h + ":" + m + ":" + s + " " + session;
document.getElementById("NowTime").innerHTML = time;
now = performance.now();
setTimeout(step, Math.max(0, nextInterval));
}
Related
I am trying to make the current time of a video display as "Minutes:Seconds:Milliseconds".
I have found a way to extract the milliseconds already from the time, since currentTime already displays as "seconds.milliseconds".
I am wondering if there is a more efficent way to extract the milliseconds from the specified time.
var video = document.querySelector("video");
function showTime() {
var time = video.currentTime;
var m = Math.floor(time / 60);
var s = Math.floor(time % 60);
var ms = (time - Math.floor(time)).toFixed(3).toString();
ms = ms.split(".").slice(1);
if (m < 10) {
m = "0" + m;
}
if (s < 10) {
s = "0" + s;
}
var timeFormat = m + ":" + s + ":" + ms;
return timeFormat;
}
I use a script that coverts Earth Time into an in-game time for a game (Eorzea Time). The script that was originally written is here.
My issue is that this pulls the Earth Time from the user's device clock. So if the clock is not correct on their device the conversion to Eorzea time is not accurate.
I'd like to pull Earth Time from a clock that is guaranteed to be accurate. I've been unable to figure out how to do this.
As an example. If you view this script alongside this site (www.ffxivclock.com) and change your time by even a minute or two...the jsfiddle clock will be off while the ffxivclock.com time will still be correct.
var E_TIME = 20.5714285714;
var global = {
utcTime: null,
eorzeaTime: null
};
window.setInterval(updateClock, Math.floor(1000 * 60 / E_TIME));
function updateClock() {
global.utcTime = new Date().getTime();
var eo_timestamp = Math.floor(global.utcTime * E_TIME);
global.eorzeaTime = new Date();
global.eorzeaTime.setTime(eo_timestamp);
showTime();
}
function showTime() {
var d = new Date();
d.setTime(global.eorzeaTime);
var eTime = document.getElementById('e-time');
var hours = d.getUTCHours();
var ampm = hours > 11 ? "PM" : "AM";
if(hours > 12)
hours -= 12;
hours = padLeft(hours);
var minutes = d.getUTCMinutes();
minutes = padLeft(minutes);
eTime.innerHTML = hours + ":" + minutes + " " + ampm;
}
function padLeft(val){
var str = "" + val;
var pad = "00";
return pad.substring(0, pad.length - str.length) + str;
}
updateClock();
My javascriptcode is working fine when i put alert.I need to Display time in Counter Format(Second decreasing way). Please help me in resolving this issue
<script type="text/javascript">
window.onload = function () {
//alert("request>>>");
var count = 0;
var start_actual_time = document.getElementById("timerStartTime").value;
var end_actual_time = document.getElementById("timerEndTime").value;
start_actual_time = new Date(start_actual_time);
var start_actual_time1 = new Date(start_actual_time.getTime());
start_actual_time1 = new Date(start_actual_time1);
var end_actual_time1 = new Date(end_actual_time);
var hours =end_actual_time1.getHours()- start_actual_time1.getHours();
var minutes = end_actual_time1.getMinutes() - start_actual_time1.getMinutes();
var seconds = end_actual_time1.getSeconds()- start_actual_time1.getSeconds();
seconds = hours * 3600 + minutes * 60 + seconds;
//alert ("seconds >>." +seconds);
timer(seconds);
};
function timer(seconds) {
alert("calling timer");
var s1 = Number(seconds);
var hours = Math.floor(s1 / 3600);
var minutes = Math.floor(s1 % 3600 / 60);
var s = Math.floor(s1 % 3600 % 60);
//alert("sec1" + s);
display = document.querySelector('#time');
var formatted = ((hours < 10)?("0" + hours):hours) + ":" + ((minutes < 10)?("0" + minutes):minutes) + ":" + ((s < 10)?("0" + s):s)
display.textContent = formatted ;
seconds = seconds - 1;
timer(seconds);
}
</script>
The way your code is written creates a
too much recursion
exception for me.
Therefore I have avoided recursive invokes and used javascript setInterval:
var refreshIntervalId = setInterval(function(){ timer(); }, 1000);
When your seconds reach zero, timer is stopped:
if (seconds == -1){
clearInterval(refreshIntervalId);
Link to working fiddle: http://jsfiddle.net/3ggspruf/2/
I need to make countdown timer for every day to 21:00. Counting till live stream.
If time is less then 21:00 display the time left and if time is from 21:00-22:00
I would like to display 'streaming right now'. After 22:00 start counting till tomorrow at 21:00.
Any suggestins how to do this?
Here is what I tried so far but it doesn't work well and also if client change the time on his computer the counter will change. I need to fix that on server side so for everyone it will show the same time.
<script type="text/javascript">
$(document).ready(function(){
var curT, tarT, difT;
curT = new Date().getTime()/1000;
tarT = new Date('<?php echo (new DateTime('May 05, 2014'))->add(new DateInterval("P1D"))->format('M d, Y');?>, 21:00:00').getTime()/1000;
init();
function init(){
var d,h,m,s;
difT = tarT - curT;
function updateT(){
s = difT;
d = Math.floor(s/86400);
s -= d * 86400;
h = Math.floor(s/3600);
s -= h * 3600;
m = Math.floor(s/60);
s -= m * 60;
s = Math.floor(s);
}
function tick(){
clearTimeout(timer);
updateT();
displayT();
if(difT>0){
difT--;
timer = setTimeout(tick,1*1000);
} else {
$('.timeleft').html('Aukcija u toku...');
}
}
function displayT(){
var out;
out = h+":"+m+":"+s;
$('.timeleft').html(out);
}
var timer = setTimeout(tick,1*1000);
}
});
</script>
Since you need a combination of both scripts from above, I combined them for you: http://jsfiddle.net/69TAf/
Reads out the real time from GMT Server
Clients timezone doesn't matter
GMT Server is only pinged once at beginning (for better performance)
Added leading zeros so it looks better
Credits to edcs and Miskone!
var date;
var display = document.getElementById('time');
$(document).ready(function() {
getTime('GMT', function(time){
date = new Date(time);
});
});
setInterval(function() {
date = new Date(date.getTime() + 1000);
var currenthours = date.getHours();
var hours;
var minutes;
var seconds;
if (currenthours != 21){
if (currenthours < 21) {
hours = 20 - currenthours;
} else {
hours = 21 + (24 - currenthours);
}
minutes = 60 - date.getMinutes();
seconds = 60 - date.getSeconds();
if (minutes < 10) {
minutes = '0' + minutes;
}
if (seconds < 10) {
seconds = '0' + seconds;
}
display.innerHTML = hours + ':' + minutes + ':' +seconds;
} else {
display.innerHTML = 'LIVE NOW';
}
}, 1000);
function getTime(zone, success) {
var url = 'http://json-time.appspot.com/time.json?tz=' + zone,
ud = 'json' + (+new Date());
window[ud]= function(o){
success && success(new Date(o.datetime));
};
document.getElementsByTagName('head')[0].appendChild((function(){
var s = document.createElement('script');
s.type = 'text/javascript';
s.src = url + '&callback=' + ud;
return s;
})());
}
And html:
<div id='time'></div>
If you don't want to ping an external server for getting the time, you can use this fiddle (not working on jsfiddle, since contains php):
http://jsfiddle.net/qQ6V3/ - I think it's even better this way.
If you need everyone to be counting down from the same time, then you'll need to grab it from a centralised time server. This code does exactly that:
function getTime(zone, success) {
var url = 'http://json-time.appspot.com/time.json?tz=' + zone,
ud = 'json' + (+new Date());
window[ud]= function(o){
success && success(new Date(o.datetime));
};
document.getElementsByTagName('head')[0].appendChild((function(){
var s = document.createElement('script');
s.type = 'text/javascript';
s.src = url + '&callback=' + ud;
return s;
})());
}
getTime('GMT', function(time){
// This is where you do whatever you want with the time:
alert(time);
});
Source
If you use getTime() instead of grabbing the local time from the client then everyone will be in sync.
you can do something like this :
<div id='time'></div>
and the script :
var display = document.getElementById('time');
setInterval(function(){
var date = new Date();
var currenthours = date.getHours();
var hours;
var minutes;
var secondes;
if (currenthours != 21){
if (currenthours < 21)
hours = 20 - currenthours;
else hours = 21 + (24 - currenthours);
minutes = 60 - date.getMinutes();
secondes = 60 - date.getSeconds();
display.innerHTML = hours + ':' + minutes + ':' +secondes;
}
else display.innerHTML = 'LIVE NOW';
},1000);
fiddle: http://jsfiddle.net/KbM8D/
Lots of answers, one more won't hurt. :-)
I think you are best to pass the start and end of streaming to the client as a UNIX UTC time values in seconds. Then the client can turn that into a local date and count down to that. Using a network time server sounds good, but it means that everyone must use the same time server and you are reliant on the server being available.
if you're going to pass a time at all, it might as well be the start and end according to your server. You can even pass the current time from the server and calculate a time offset to apply at the client. Anyhow, the code…
<script>
var countDown = (function() {
var startStream;
var endStream;
var streamingText = 'streaming right now';
var updateElement;
// Pad single digit numbers
function pad(n) {
return (n<10?'0':'') + +n;
}
// Format a time difference as hh:mm:ss
// d0 and d1 are date objects, d0 < d1
function timeDiff(d0, d1) {
var diff = d1 - d0;
return pad(diff/3.6e6|0) + ':' + pad((diff%3.6e6)/6e4|0) + ':' + pad(diff%6e4/1000|0);
}
// start, end are UNIX UTC time values in seconds for the start and end of streaming
return function(elementId, start, end) {
var now = new Date();
var returnValue;
// By default, run again just after next full second
var delay = 1020 - now.getMilliseconds();
// turn start and end times into local Date objects
if (start) startStream = new Date(start*1000);
if (end) endStream = new Date(end*1000);
// If now is after endStream, add 1 day,
// Use UTC to avoid daylight saving adjustments
if (now > endStream) {
endStream.setUTCHours(endStream.getUTCHours() + 24);
startStream.setUTCHours(startStream.getUTCHours() + 24);
}
// Store the element to write the text to
if (elementId) updateElement = document.getElementById(elementId);
// If it's streaming time, return streaming text
if (now >= startStream && now < endStream) {
returnValue = streamingText;
// Run again after streaming end time
delay = endStream - now;
} else {
// Otherwise, count down to startStream
returnValue = timeDiff(now, startStream);
}
// Write the time left or streaming text
updateElement.innerHTML = returnValue;
// Call again when appropriate
setTimeout(countDown, delay);
};
}());
// Testing code
// Create dates for a local time of 21:00 today
var myStart = new Date();
myStart.setHours(21,0,0,0);
var myEnd = new Date()
myEnd.setHours(22,0,0,0);
// Create UNIX time values for same time as UTC
var startUTCTimeValue = myStart/1000|0
var endUTCTimeValue = myEnd/1000|0
// Run when page loads
window.onload = function() {
countDown('foo', startUTCTimeValue, endUTCTimeValue);
}
</script>
<div id="foo"></div>
How do I show the current time in the format HH:MM:SS?
You can use native function Date.toLocaleTimeString():
var d = new Date();
var n = d.toLocaleTimeString();
This will display e.g.:
"11:33:01"
MDN: Date toLocaleTimeString
var d = new Date();
var n = d.toLocaleTimeString();
alert("The time is: \n"+n);
function checkTime(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
function startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
// add a zero in front of numbers<10
m = checkTime(m);
s = checkTime(s);
document.getElementById('time').innerHTML = h + ":" + m + ":" + s;
t = setTimeout(function() {
startTime()
}, 500);
}
startTime();
<div id="time"></div>
DEMO using javaScript only
Update
Updated Demo
(function () {
function checkTime(i) {
return (i < 10) ? "0" + i : i;
}
function startTime() {
var today = new Date(),
h = checkTime(today.getHours()),
m = checkTime(today.getMinutes()),
s = checkTime(today.getSeconds());
document.getElementById('time').innerHTML = h + ":" + m + ":" + s;
t = setTimeout(function () {
startTime()
}, 500);
}
startTime();
})();
You can do this in Javascript.
var time = new Date();
console.log(time.getHours() + ":" + time.getMinutes() + ":" + time.getSeconds());
At present it returns 15:5:18. Note that if any of the values are less than 10, they will display using only one digit, not two.
Check this in JSFiddle
Updates:
For prefixed 0's try
var time = new Date();
console.log(
("0" + time.getHours()).slice(-2) + ":" +
("0" + time.getMinutes()).slice(-2) + ":" +
("0" + time.getSeconds()).slice(-2));
You can use moment.js to do this.
var now = new moment();
console.log(now.format("HH:mm:ss"));
Outputs:
16:30:03
new Date().toTimeString().slice(0,8)
Note that toLocaleTimeString() might return something like 9:00:00 AM.
Use this way:
var d = new Date();
localtime = d.toLocaleTimeString('en-US', { hour12: false });
Result: 18:56:31
function realtime() {
let time = moment().format('h:mm:ss a');
document.getElementById('time').innerHTML = time;
setInterval(() => {
time = moment().format('h:mm:ss a');
document.getElementById('time').innerHTML = time;
}, 1000)
}
realtime();
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.min.js"></script>
<div id="time"></div>
A very simple way using moment.js and setInterval.
setInterval(() => {
moment().format('h:mm:ss a');
}, 1000)
Sample output
Using setInterval() set to 1000ms or 1 second, the output will refresh every 1 second.
3:25:50 pm
This is how I use this method on one of my side projects.
setInterval(() => {
this.time = this.shared.time;
}, 1000)
Maybe you're wondering if using setInterval() would cause some performance issues.
Is setInterval CPU intensive?
I don't think setInterval is inherently going to cause you significant performance problems. I suspect the reputation may come from an earlier era, when CPUs were less powerful. ... - lonesomeday
No, setInterval is not CPU intensive in and of itself. If you have a lot of intervals running on very short cycles (or a very complex operation running on a moderately long interval), then that can easily become CPU intensive, depending upon exactly what your intervals are doing and how frequently they are doing it. ... - aroth
But in general, using setInterval really like a lot on your site may slow down things. 20 simultaneously running intervals with more or less heavy work will affect the show. And then again.. you really can mess up any part I guess that is not a problem of setInterval. ... - jAndy
new Date().toLocaleTimeString('it-IT')
The it-IT locale happens to pad the hour if needed and omits PM or AM 01:33:01
Compact clock function:
setInterval(function() {
let d = new Date()
console.log(`${d.getHours()}:${d.getMinutes()}:${d.getSeconds()}`)
}, 1000);
This code will output current time in HH:MM:SS format in console, it takes into account GMT timezones.
var currentTime = Date.now()
var GMT = -(new Date()).getTimezoneOffset()/60;
var totalSeconds = Math.floor(currentTime/1000);
seconds = ('0' + totalSeconds % 60).slice(-2);
var totalMinutes = Math.floor(totalSeconds/60);
minutes = ('0' + totalMinutes % 60).slice(-2);
var totalHours = Math.floor(totalMinutes/60);
hours = ('0' + (totalHours+GMT) % 24).slice(-2);
var timeDisplay = hours + ":" + minutes + ":" + seconds;
console.log(timeDisplay);
//Output is: 11:16:55
This is an example of how to set time in a div(only_time) using javascript.
function date_time() {
var date = new Date();
var am_pm = "AM";
var hour = date.getHours();
if(hour>=12){
am_pm = "PM";
}
if (hour == 0) {
hour = 12;
}
if(hour>12){
hour = hour - 12;
}
if(hour<10){
hour = "0"+hour;
}
var minute = date.getMinutes();
if (minute<10){
minute = "0"+minute;
}
var sec = date.getSeconds();
if(sec<10){
sec = "0"+sec;
}
document.getElementById("time").innerHTML = hour+":"+minute+":"+sec+" "+am_pm;
}
setInterval(date_time,500);
<per>
<div class="date" id="time"></div>
</per>
new Date().toLocaleTimeString()
function realtime() {
let time = moment().format('hh:mm:ss.SS a').replace("m", "");
document.getElementById('time').innerHTML = time;
setInterval(() => {
time = moment().format('hh:mm:ss.SS A');
document.getElementById('time').innerHTML = time;
}, 0)
}
realtime();
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.min.js"></script>
<div id="time"></div>
Use
Date.toLocaleTimeString()
// Depending on timezone, your results will vary
const event = new Date('August 19, 1975 23:15:30 GMT+00:00');
console.log(event.toLocaleTimeString('en-US'));
// expected output: 1:15:30 AM
console.log(event.toLocaleTimeString('it-IT'));
// expected output: 01:15:30
console.log(event.toLocaleTimeString('ar-EG'));
// expected output: ١٢:١٥:٣٠
Source