I am in need of virtual time (4 x current date and time). I have managed to display the running clock with the current date and time, but I am unable to the time four times faster than current time.
For example, if the current date is 01-01-2012 00:00:00, the virtual time should
be 01-01-2012 00:00:04
Not only the seconds alone should get multiplied; the corresponding minutes, hours, date, month and year also should get multiplied when seconds crosses 59 virtual seconds. That is, the clock should run live with incremental of four seconds for every second with my date format.
Please see my page: http://www.chemfluence.org.in/sample.html
It's now running with the current time. I want to run this four times faster.
Please see my code below.
<!DOCTYPE html>
<html>
<head>
<script>
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('txt').innerHTML =
today.getDate() +
"-" +
(today.getMonth()+1)+"-" +
today.getFullYear() +
" "+h+":"+m+":"+s;
t = setTimeout(function(){startTime()},500);
}
function checkTime(i)
{
if (i<10)
{
i = "0" + i;
}
return i;
}
</script>
</head>
<body onload="startTime()">
<div id="txt"></div>
</body>
</html>
There is a simple formula to determine the virtual time for every given time, knowing the two timestamps and the factor:
var virtualOrigin = Date.parse("2012-01-01T00:00:04"),
realOrigin = Date.parse("2012-01-01T00:00:00"),
factor = 4;
function getVirtual(time) {
return new Date( virtualOrigin + (time - realOrigin) * factor );
}
// usage:
var now = new Date(),
toDisplay = getVirtual(now);
Demo at jsfiddle.net
determine the current time ("START") (as timestamp -- count of seconds since 1970)
when displaying the clock, display (("CURRENT" - "START") * 4) + "START" instead
You can do a setInterval for 1 second and then add 4 seconds to the current date.
(This example just logs the time to the console, but you can easily hook it up to an HTML element.)
var date = new Date();
setInterval(function(){
date = new Date(date.getTime() + 4000);
console.log(date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds());
}, 1000);
Related
I am using this code to display the current time on a site I'm building.
https://www.w3schools.com/js/tryit.asp?filename=tryjs_timing_clock
Could someone tell me what code to add in order change the time to a different time zone? I'd also love the time to display 12 hour increments rather than 24.
Any help would be appreciated.
You can change the time zone by converting the time to UTC and adding the needed number of hours
var utc = today.getTime() + (today.getTimezoneOffset() * 60000);
var newDate = new Date(utc + (3600000 * -2));
As for converting to 12 hour format
var h = newDate.getHours() % 12;
function startTime(id, offset) {
var today = new Date();
var utc = today.getTime() + (today.getTimezoneOffset() * 60000);
var newDate = new Date(utc + (3600000 * -2));
var h = newDate.getHours() % 12;
var m = newDate.getMinutes();
var s = newDate.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('txt').innerHTML =
h + ":" + m + ":" + s;
var t = setTimeout(startTime, 500);
}
function checkTime(i) {
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body onload="startTime();">
<div id="txt"></div>
</body>
</html>
edit
As mentioned by #BrockLee in a comment - as it is it will, indeed, show 12'o clock as 0. If this is not desired, you could change the line that sets the hours to, for example,
var h = (newDate.getHours() % 12 == 0) ? 12 : newDate.getHours() % 12;
In that example, you could use today.toLocaleTimeString() instead to show it in the preferred format of current user's locale.
Also, MDN's documentation on Date/Time related functionality in JavaScript will probably be much more helpful.
For auction web app I want to run a timer after getting time from firebase-database, how to decrease time by one second using setInterval() in ReactJS
I tried below code that is increasing time but I want decrease
function display()
{
var today = new Date();
var month = today.getMonth();
var day = today.getDay();
var year = today.getFullYear();
var hour = today.getHours() > 12 ? today.getHours() - 12 : today.getHours();
var minute = today.getMinutes();
var seconds = today.getSeconds();
var output = month + '/' + day + '/' + year + ' - ' +
hour + ':' + minute + ':' + seconds + ':';
console.log(output)
}
var timer = setInterval(display,1000)
console.log(timer)
You need to compare against some time when working with setInterval in this fashion. The time returned from the server is perfect for this. The psuedo-code is provided
setInterval(function() {
var difference = timeFromServer - Date.now();
console.log(formatDate(difference));
}, 1000);
Below is a code the figure out the hour and minutes past since 8:30 AM based on the system clock, this is used for internal purposes only so I'm not fussed with the best practices
<html>
<head>
<title>Time Past Since</title>
<meta http-equiv="Refresh" content="60">
<script>
window.resizeTo(300,100);
sd = new Date(); // Get system date (sd)
sh = sd.getHours(); // Get system hour (sh)
sm = sd.getMinutes(); // Get system minutes (sm)
wh = (08); // Specify work start hour (wh)
wm =(30); // Specify work start minute (wh)
ts = ((sh *60 + sm) - (wh *60 + wm)); // Specify time since (ts) in minutes
hs = Math.floor(ts/60); // Convert the hours (hs)
ms = Math.round((ts/60 % 1) * 60); // Convert the minutes (ms)
fh = hs < 10 ? "0" : "" // Format Hours (fh)
fm = ms < 10 ? "0" : "" // Format Minutes (fm)
</script>
</head>
<body>
<center><script>document.write(fh + hs + " hours " + fm + ms + " minutes."); </script></center>
As you can see I'm using a meta to refresh the page every 60 seconds, what I'd prefer is a alternative to the document.write that calculates the difference.
I know that inline html is an alternative but I can't seem to get it to work, a working example of my code would be fantastic, thanks in advance.
Below is a snippet that does what I believe you want to do. I used your code, as requested although there are more efficient ways to calculate the difference between two times. See this SO question if you are interested.
<html>
<head>
<title>Time Past Since</title>
</head>
<body>
<center id="time">Test</center>
<script>
window.resizeTo(300,100);
updateTime();
setInterval(updateTime, 60000);
function updateTime() {
sd = new Date(); // Get system date (sd)
sh = sd.getHours(); // Get system hour (sh)
sm = sd.getMinutes(); // Get system minutes (sm)
wh = (08); // Specify work start hour (wh)
wm =(30); // Specify work start minute (wh)
ts = ((sh *60 + sm) - (wh *60 + wm)); // Specify time since (ts) in minutes
hs = Math.floor(ts/60); // Convert the hours (hs)
ms = Math.round((ts/60 % 1) * 60); // Convert the minutes (ms)
fh = hs < 10 ? "0" : ""; // Format Hours (fh)
fm = ms < 10 ? "0" : ""; // Format Minutes (fm)
document.getElementById("time").innerHTML = fh + hs + " hours " + fm + ms + " minutes.";
}
</script>
</body>
</html>
I wrapped the time calculation in a function called updateTime and makes it run every 60 seconds. It updates the text without the need to refresh.
I named the function instead of making it an anonymous function because we need to call it once when the page is first loaded.
Don't forget to click the green "accept answer" button if I answered your question!
Not the cleanest way to do this, but sounds like you don't really care.
<html>
<head>
<title>Time Past Since</title>
<script>
window.resizeTo(300,100);
setInterval(function(){
var sd = new Date(), // Get system date (sd)
sh = sd.getHours(), // Get system hour (sh)
sm = sd.getMinutes(), // Get system minutes (sm)
wh = (08), // Specify work start hour (wh)
wm =(30), // Specify work start minute (wh)
ts = ((sh *60 + sm) - (wh *60 + wm)), // Specify time since (ts) in minutes
hs = Math.floor(ts/60), // Convert the hours (hs)
ms = Math.round((ts/60 % 1) * 60), // Convert the minutes (ms)
fh = hs < 10 ? "0" : "", // Format Hours (fh)
fm = ms < 10 ? "0" : "", // Format Minutes (fm)
str = fh + hs + " hours " + fm + ms + " minutes.";
document.getElementById('display').innerHTML = str;
}, 60000);
</script>
</head>
<body>
<div><center id="display"></center></div>
</body>
</html>
I'm having an issue with a timer i'm working on, what should happen is that the counter should countdown to a specific time which is defined by me. However for some reason the time i have defined is just ignored and it counts down to the next hour. What i am essentially trying to do is set a timer that will count down the time left to a number of specific times, so far i cannot even get it to work for one single defined time. I've attached a JsFiddle which contains all relevant code. Also would it possible to store the times in an array and have the timer count down to each defined time? Thanks in advance!
var definedTime = new Date('Jan 31, 2015 05:00'); // military time to countdown TO
function ShowTimes() {
var now = new Date();
var hrs = definedTime.getHours() - now.getHours() - 1;
if (hrs < 0) {
hrs += 24;
}
var mins = 59 - now.getMinutes();
var secs = 59 - now.getSeconds();
var str = '';
str = now.toString();
str += '<br>Time until 05:00';
str += '<br>'+hrs+' hours ' + mins + ' minutes ' + secs + ' seconds';
document.getElementById('timer').innerHTML = str;
}
var _cntDown;
function StopTimes() {
clearInterval(_cntDown);
}
<body onload="_cntDown=setInterval('ShowTimes()',1000)">
<div id="timer"></div>
<button onclick="StopTimes()">Stop</button>
</body>
I trying to create a very simple time difference calculation. Just "endtime - starttime". I'm getting +1 hour though. I suspect it has with my timezone to do, since I'm GMT+1.
Regardless, that should not affect the difference, since both start and end times are in the same timezone.
Check my running example-code here:
http://jsfiddle.net/kaze72/Rm3f3/
$(document).ready(function() {
var tid1 = (new Date).getTime();
$("#tid").click(function() {
var nu = (new Date).getTime();
var diff = new Date(nu - tid1);
console.log(diff.getUTCHours() + ":" +
diff.getUTCMinutes() + ":" +
diff.getUTCSeconds());
console.log(diff.toLocaleTimeString());
});
})
You must understand what Date object represent and how it stores dates. Basically each Date is a thin wrapper around the number of milliseconds since 1970 (so called epoch time). By subtracting one date from another you don't get a date: you just get the number of milliseconds between the two.
That being said this line doesn't have much sense:
var diff = new Date(nu - tid1);
What you really need is:
var diffMillis = nu - tid1;
...and then simply extract seconds, minutes, etc.:
var seconds = Math.floor(diffMillis / 1000);
var secondsPart = seconds % 60;
var minutes = Math.floor(seconds / 60);
var minutesPart = minutes % 60;
var hoursPart = Math.floor(minutes / 60);
//...
console.log(hoursPart + ":" + minutesPart + ":" + secondsPart);
Working fiddle.