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>
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.
So the code below is the code that I was able to work with so far; however, doesn't do exactly what I need it to do.
I want to be able to call a function (aka: sundayDelta() ), however, I would love to be able to define the day of week and time of day I want the function to use in the countdown inside the calling of the function. I'm not sure if this is possible...but I was thinking something like this
sundayDelta(1,1000) which would turn into Day of Week Sunday and time of day: 1000 (10:00am). Not sure if something like this is even possible; however, I'm hoping it is. I plan on having multiple countdowns going on the same page just appearing at different times of day.
When the countdown finishes, I want it to refresh a div (doesn't matter what name the div has)
I would also love to be able to incorporate PHP server time into this that way everyone is seeing the correct countdown no matter where they are.
Any help would be great! Thanks for your input!
function plural(s, i) {
return i + ' ' + (i > 1 ? s + 's' : s);
}
function sundayDelta(offset) {
// offset is in hours, so convert to miliseconds
offset = offset ? offset * 20 * 20 * 1000 : 0;
var now = new Date(new Date().getTime() + offset);
var days = 7 - now.getDay() || 7;
var hours = 10 - now.getHours();
var minutes = now.getMinutes() - 00 ;
var seconds = now.getSeconds()- 00;
if (hours < 0){
days=days-1;
}
var positiveHours= -hours>0 ? 24-(-hours) : hours;
return [plural('day', days),
plural('hour', positiveHours),
plural('minute', minutes),
plural('second', seconds)].join(' ');
}
// Save reference to the DIV
$refresh = $('#refresh');
$refresh.text('This page will refresh in ' + sundayDelta());
// Update DIV contents every second
setInterval(function() {
$refresh.text('This page will refresh in ' + sundayDelta());
}, 1000);
When I make flexible text for intervals, I like to subtract out until nothing is left. That way you only show the non-0 values:
function sundayDelta(target_date) {
var now = new Date();
var offset = Math.floor((Date.parse(target_date) - now.valueOf()) / 1000);
var r = [];
if (offset >= 86400) {
var days = Math.floor(offset / 86400);
offset -= days * 86400;
r.push(plural('day', days));
}
if (offset >= 3600) {
var hours = Math.floor(offset / 3600);
offset -= hours * 3600;
r.push(plural('hour', hours));
}
if (offset >= 60) {
var minutes = Math.floor(offset / 60);
offset -= minutes * 60;
r.push(plural('minute', minutes));
}
if (offset != 0) {
r.push(plural('second', offset));
}
return r.join(' ');
}
In the PHP code, you can set variable this way. And we'll leave time zones out of it for now, but they could be added as well just by specifying them.
echo "target_date = '" . date('Y-m-d H:i:s', strotime('next Sunday 10am')) . "';\n";
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);
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.
I've got this js:
<script>
$('#appt_start').val(parent.location.hash);
$('#appt_end').val(parent.location.hash);
</script>
which gets the hash value from the url something.com/diary.php#0800 for example.
The value is then used to autofill the start and end times in an appointment form.
I need the second time (#appt_end) to be incremented by 15 minutes? Any ideas how I do this, my js is rubbish...
Thanks!
EDIT
Here's the working code I'm now using:
// add the time into the form
var hashraw = parent.location.hash;
var minIncrement = 15; // how many minutes to increase
hash = hashraw.replace("#", ""); // remove the hash
// first we split the time in hours and mins
var hours = parseInt(hash.substring(0, 2),10); // get hours (first 2 chars)
var mins = parseInt(hash.substring(2, 4),10); // get mins (last 2 chars)
// add the new minutes, and enforce it to fit 60 min hours
var newMins = (mins + minIncrement )%60;
// check if the added mins changed thehour
var newHours = Math.floor( (mins + minIncrement ) / 60 );
// create the new time string (check if hours exceed 24 and restart it
// first we create the hour string
var endTime = ('0' + ((hours+newHours)%24).toString()).substr(-2);
// then we add the min string
endTime += ('0'+ newMins.toString()).substr(-2);
$('#appt_start').val(hash);
$('#appt_end').val( endTime );
You need to split the time in hours / mins and then apply time logic to it to increase it..
var hash = parent.location.hash.replace('#','');
var minIncrement = 15; // how many minutes to increase
// first we split the time in hours and mins
var hours = parseInt(hash.substring(0, 2),10); // get hours (first 2 chars)
var mins = parseInt(hash.substring(2, 4),10); // get mins (last 2 chars)
// add the new minutes, and enforce it to fit 60 min hours
var newMins = (mins + minIncrement )%60;
// check if the added mins changed thehour
var newHours = Math.floor( (mins + minIncrement ) / 60 );
// create the new time string (check if hours exceed 24 and restart it
// first we create the hour string
var endTime = ('0' + ((hours+newHours)%24).toString()).substr(-2);
// then we add the min string
endTime += ('0'+ newMins.toString()).substr(-2);
$('#appt_start').val( hash );
$('#appt_end').val( endTime );
Check it out at http://www.jsfiddle.net/gaby/cnnBc/
try this:
<script>
$(function() {
$('#appt_start').val(parent.location.hash);
var end = parent.location.hash;
end = end.replace("#", "");
end = (end * 1) + 15;
if (end < 1000) {end = '0' + end};
$('#appt_end').val(end);
});
</script>
Would it be possible like this?
Working Demo
var hash="08:00";
$('#appt_start').val(hash);
var d = new Date("October 13, 1975 "+hash)
d.setMinutes(d.getMinutes()+15);
$('#appt_end').val(d.getHours()+":"+d.getMinutes());
You use a fictitious date so to sum the minutes.
If the hash has not the ":", you can do a substring to insert the ":".