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.
Related
I am trying to make a JavaScript countdown timer to UTC midnight that works in a browser (which typically converts to local time).
It seems to work most of the time, but for some reason it will go negative sometimes. I want it to always display time until midnight UTC.
-3 hours 23 minutes 34 seconds
I'm pretty sure I tested this on crossing midnight, but lately it's been going negative like it isn't pulling a new date.
Here is what I am using now on my website.
setInterval(() => {
let toDate = new Date()
let tomorrow = new Date()
tomorrow.setHours(24, 0, 0, 0)
let diffMS =
tomorrow.getTime() / 1000 -
toDate.getTime() / 1000 -
toDate.getTimezoneOffset() * 60
let diffHr = Math.floor(diffMS / 3600)
diffMS = diffMS - diffHr * 3600
let diffMi = Math.floor(diffMS / 60)
diffMS = diffMS - diffMi * 60
let diffS = Math.floor(diffMS)
let result = diffHr + ' hours '
result += diffMi + ' minutes '
result += diffS + ' seconds '
this.timeRemaining = result
}, 1000)
Not sure exactly where your issue is from, but using local time adjusted by offset is somewhat fraught. Also the offset changes over a DST boundary so that might be an issue too (or not) so the countdown will jump the equivalent of the change in offset (either + or -).
It's very much simpler to set the end using UTC methods and count down to that, e.g.
// Return time to next UTC midnight as x hours x minutes x seconds
function toMidnightUTC(date = new Date()) {
let d = new Date(+date);
d.setUTCHours(24,0,0,0);
let diff = d - date;
return `${diff/3.6e6 |0} hours ` +
`${diff%3.6e6 / 6e4 |0} minutes ` +
`${diff%6e4 / 1000 |0} seconds`;
}
// Run 20ms after next full second
let runIt = ()=> {
document.getElementById('s0').textContent = toMidnightUTC();
let lag = 1020 - new Date() % 6e4;
setTimeout(runIt, lag);
};
// Start the process…
runIt();
<span id="s0"></span>
Note that setInterval isn't a good way to do a countdown as the interval is not guaranteed to run every second and typically slowly drifts so it doesn't tick with the system clock and drifts, so skips a second from time to time.
Better to use setTimeout and get the time to the next full second each time so it runs very close to the system clock tick and rarely skips (though it still might if the system is working hard).
Ok on My dev machine I have the following code:
JScript
setInterval(function () { myTimer(); }, 1000);
function myTimer() {
var d = new Date();
var hrs = d.getHours();
var min = d.getMinutes();
var sec = d.getSeconds();
var dayOfWeek = d.getDay();
// Let's do this logically.
// To get the number of victims so far today we need to know how many seconds have passed so far today.
var totalSeconds = sec + (min * 60) + (hrs * 3600); // Number of Seconds passed so far today.
// Now multiply that by 14 in accordance with Symantec's research.
var VictimsToday = totalSeconds * 14;
// To get the number of victims this week we need to multiply
// The number of seconds in a day by the number of full days and add the number of seconds of this partial day.
var TotalSecondsInADay = 86400; // According to Google.
var DaysSoFarThisWeek = dayOfWeek + 1; // Removes today as a partial day.
// We already know how many seconds are in this partial day = totalSeconds
// So our calculation is
var tsD = TotalSecondsInADay * DaysSoFarThisWeek;
var VictimsThisWeek = (totalSeconds + tsD) * 14;
// Now we get the Day of the Year remove today as a partial day and calculate
// Number of seconds a day by the number of complete days so far + todays partial day
var DOY = DayOfYear();
var tsY = DOY * totalSeconds;
var VictimsThisYear = (totalSeconds + tsY) * 14;
document.getElementById("FooterStatistics").innerHTML = Intl.NumberFormat().format(VictimsToday);
document.getElementById("FooterStatistics2").innerHTML = Intl.NumberFormat().format(VictimsThisWeek);
document.getElementById("FooterStatistics4").innerHTML = Intl.NumberFormat().format(VictimsThisYear);
}
function DayOfYear() {
var today = new Date();
var first = new Date(today.getFullYear(), 0, 1);
var theDay = Math.round(((today - first) / 1000 / 60 / 60 / 24) + 0.5, 0);
return theDay;
}
With the HTML being:
BODY
<div id="FooterStatistics"></div>
<div id="FooterStatistics2"></div>
<div id="FooterStatistics4"></div>
Now on the Dev machine the calculation returned in the DIV is:
However, when I run this on W3Schools Tryit Editor: http://www.w3schools.com/js/tryit.asp?filename=tryjs_date_getday
I get a totally different calculated result:
Now I know the numbers will be different because of TimeZone differences - what should not be different is the actual calculations. The Dev machine's second result is smaller than the first which it should NEVER be, and the third result is apparently not even a number - where upon the results in the TryIt editor provide more reasonable asnwers.
How can this be?
While creating apps, keep using console.log() to check the values. This really helps to understand what is happening, in the future. This is not an alternative to debugging, though, but it helps. You could only remove them when your code is to go live, or you are sure it works and is well abstracted.
PS: Avoid using w3schools.com. Use MDN. It's much better.
Does anyone how can I do a time difference count in Javascript?
Example:
If I have the following time (24H format)
startTime = 0615
endTime = 1530
breakTime = 0030
how can I get the following output?
diffB4Break = 7.15 hours
afterBreak = 6.45 hours
There are complications here, for example you would need to know what the maximum shift was, and whether it is possible for a worker to be scheduled to work over the threshold of a day, i.e. start work at 2300 and finish at 0900.
It very quickly becomes clear why it's better to use a Date/Time object to handle dates and time-deltas.
In Javascript have a look at Date
Based on #Guffa's answer here:
function parseTime(s) {
var c = s.split(':');
return parseInt(c[0]) * 60 + parseInt(c[1]);
}
var startTime = '6:45';
var endTime = '15:30';
var diff = parseTime(endTime) - parseTime(startTime);
var min = diff % 60;
var hrs = parseInt(diff / 60);
alert(hrs + ":" + min);
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);
lol sorry i posted it accidentally
I'm new to JavaScript and i'm trying to make a simple countdown script that should show the difference between the end date and today's server date.
here is a great example of what i'm trying to do http://moblog.bradleyit.com/2009/06/javascripting-to-find-difference.html
The only thing i want to add is another variable with a calculated seconds. How can i do that?
Here is the code:
var today = new Date();
var Christmas = new Date("12-25-2009");
var diffMs = (Christmas - today); // milliseconds between now & Christmas
var diffDays = Math.round(diffMs / 86400000); // days
var diffHrs = Math.round((diffMs % 86400000) / 3600000); // hours
var diffMins = Math.round(((diffMs % 86400000) % 3600000) / 60000); // minutes
alert(diffDays + " days, " + diffHrs + " hours, " + diffMins + " minutes until Christmas 2009 =)");
You have two issues with this code:
1: You need to use a date that will be accepted across browsers so it needs to be formatted with / instead of -.
2: You are rounding, which when rounding up will give you inaccurate numbers. All numbers need to be rounded down. Here is a function do do so:
var roundDown = function(num){
var full = num.toString();
var reg = /([\d]+)/i;
var res = reg.exec(full);
return res[1];
}
So your final code should look like this:
var roundDown = function(num){
var full = num.toString();
var reg = /([\d]+)/i;
var res = reg.exec(full);
return res[1];
}
var today = new Date(); // date and time right now
var goLive = new Date("06/01/2013"); // target date
var diffMs = (goLive - today); // milliseconds between now & target date
var diffDays = roundDown(diffMs / 86400000); // days
var diffHrs = roundDown((diffMs % 86400000) / 3600000); // hours
var diffMins = roundDown(((diffMs % 86400000) % 3600000) / 60000); // minutes
var diffSecs = roundDown((((diffMs % 86400000) % 3600000) % 60000) / 1000 ); // seconds
var endDate = new Date(year, month, day, hours, minutes, seconds, milliseconds);
var today = Date.now()
var timeLeft = endDate - today // timeLeft would be in milliseconds
// Parse this into months, days, hours, ...
Put this in a function and set it up to be called every second or so using setInterval.
This should get you started with the JavaScript date object and it's associated methods.
http://www.w3schools.com/jsref/jsref_obj_date.asp
Also, look up the setInterval() method, that will allow you to fire code in set intervals (for example, updating the countdown text).