Difference between timestamps in Javascript - javascript

I just want to confirm what I have, I saw on stackoverflow that I can get do the following:
var current_time = +new Date();
console.log (current_time);
var fetch_time = +new Date();
console.log((fetch_time-current_time));
and I now I just want to know what this difference is in. milliseconds?
Log Output
1375976707028
76
I just simply want the fastest way to check if 60 seconds have passed or not. I'd rather avoid any kind of operations like multiplication or division.
Thanks

The + looks a little weird there, I'd just use .getTime().
.getTime() returns milliseconds, so compare with 60000.

try it:
var current_time = +new Date();
var fetch_time;
console.log (current_time);
setTimeout(function() {
fetch_time = +new Date();
console.log((fetch_time-current_time)); // 1000 -> ms, 1 -> s
}, 1000);

Related

Setting timezone for running clock in JavaScript

Good days guys. I have this nice and clean code for a running clock.
<script type="text/javascript">
function DisplayTime(){
if (!document.all && !document.getElementById)
return
timeElement=document.getElementById? document.getElementById("curTime"): document.all.tick2
var CurrentDate=new Date()
var hours=CurrentDate.getHours()
var minutes=CurrentDate.getMinutes()
var seconds=CurrentDate.getSeconds()
var DayNight="PM"
if (hours<12) DayNight="AM";
if (hours>12) hours=hours-12;
if (hours==0) hours=12;
if (minutes<=9) minutes="0"+minutes;
if (seconds<=9) seconds="0"+seconds;
var currentTime=hours+":"+minutes+":"+seconds+" "+DayNight;
timeElement.innerHTML="<font style='font-family:Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800&subset=latin,cyrillic-ext,latin-extfont-size:14px;color:#fff;'>"+currentTime+"</b>"
setTimeout("DisplayTime()",1000)
}
window.onload=DisplayTime
</script>
My only problem is it's based the system time. How can I set the timezone so that it will display the correct time based on the timezone specified?
There's nothing built into the JavaScript Date object that handles any timezones other than local (system) time and UTC.
You can do it by giving your Date instance the wrong time, using the delta between one of those timezones (local or UTC) and the time zone you want to use. It's easier if you use UTC.
So for instance, say we want our time in GMT+01:00:
var dt = new Date();
dt.setTime(dt.getTime() + (60 * 60 * 1000));
// ^^^^^^^^^^^^^^---- one hour in milliseconds,
// which is our offset from UTC/GMT
var hours = dt.getUTCHours(); // Use UTC methods to get time
var minutes = dt.getUTCMinutes();
var seconds = dt.getUTCSeconds();
Time stuff, particularly with timezones, is hard. You might look at using a library for it, although for just this sort of clock that would be overkill. One good library is MomentJS (which has a timezone add-on).
You can use getTimezoneOffset method of the Date object. It gives you the timezone offset, according to your timezone in minutes.
So in order to get the current time in UTC (+0 timezone) you can do something of the sort:
var tzOffset = CurrentDate.getTimezoneOffset();
// some timezones are not set hours, so we must calculate the minutes
var minutesOffset = parseInt(tzOffset%60,10);
// the offset hours for the timezone
var hoursOffset = parseInt(tzOffset/60, 10);
Then you need to do some math in your code to account for the offset:
var hours = CurrentDate.getHours() + hoursOffset;
var minutes = CurrentDate.getMinutes() + minutesOffset;
This would account for your timezone. If you want to calculate another timezone, that you specify, change the tzOffset above to show your timezone.
var tzOffset = CurrentDate.getTimezoneOffset() + TIMEZONE_HOURS*60;
TIMEZONE_HOURS is the timezone in hours you want, e.g. if you want UTC+3, you must set TIMEZONE_HOURS to 3.
As a whole timezones are a bit complicated task because they change a lot and there are some caveats with them. If you want to dwell more into this, check this answer in another question on SO
I have implemented your working code by adding one more function to obtain what you want. See this will help
function DisplayTime(timeZoneOffsetminutes){
if (!document.all && !document.getElementById)
return
timeElement=document.getElementById? document.getElementById("curTime"): document.all.tick2
var requiredDate=getTimeZoneTimeObj(timeZoneOffsetminutes)
var hours=requiredDate.h;
var minutes=requiredDate.m;
var seconds=requiredDate.s;
var DayNight="PM";
if (hours<12) DayNight="AM";
if (hours>12) hours=hours-12;
if (hours==0) hours=12;
if (minutes<=9) minutes="0"+minutes;
if (seconds<=9) seconds="0"+seconds;
var currentTime=hours+":"+minutes+":"+seconds+" "+DayNight;
timeElement.innerHTML="<font style='font-family:Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800&subset=latin,cyrillic-ext,latin-extfont-size:14px;color:#fff;'>"+currentTime+"</b>"
setTimeout("DisplayTime(-330)",1000)
}
window.onload=DisplayTime(-330);
function getTimeZoneTimeObj(timeZoneOffsetminutes){
var localdate = new Date()
var timeZoneDate = new Date(localdate.getTime() + ((localdate.getTimezoneOffset()- timeZoneOffsetminutes)*60*1000));
return {'h':timeZoneDate.getHours(),'m':timeZoneDate.getMinutes(),'s':timeZoneDate.getSeconds()};
}
#curTime{
background-color:#000;
}
<div id="curTime"></div>
visit this link as a reference
example:
var x = new Date();
var currentTimeZoneOffsetInHours = x.getTimezoneOffset() / 60;
You can try using moment.js
It is very nice library which handles timezones too.

Calculating time difference in milliseconds for two given times with "DD/MM/YYYY HH:mm:ss:ms" format in javascript

I have two times.
StartTime :"2014/10/28 11:50:28:318"
EndTime : "2014/10/28 11:50:35:249"
I need to calculate the difference between them in milliseconds. I used moment to calculate it.
My Code:
var msElapsedTime = moment(EndTime , "DD/MM/YYYY HH:mm:ss:sss").diff(moment(StartTime , "DD/MM/YYYY HH:mm:ss:sss"));
Answer: 7000
It shows as milliseconds but taking a round value.
The parsing token for milliseconds is SSS, not ms or sss. Your date tokens were also in the wrong order.
var StartTime = "2014/10/28 11:50:28:318",
EndTime = "2014/10/28 11:50:35:249";
var msElapsedTime = moment(EndTime, "YYYY/MM/DD HH:mm:ss:SSS").diff(moment(StartTime , "YYYY/MM/DD HH:mm:ss:SSS"))
alert(msElapsedTime); // 6931
Here's some pure JS:
var StartTime = new Date("2014/10/28 11:50:28:318");
var EndTime = new Date("2014/10/28 11:50:35:249");
console.log(EndTime - StartTime); // 6931
JSFIDDLE.
Construct it like this
var msElapsedTime = moment('2014/10/28 11:50:28.318').diff(moment('2014/10/28 11:50:35.249'));

Best Way to detect midnight and reset data

I've been developing a web application Dashboard and I was wondering how to detect that is midnight in order to reset some arrays that contains datas from the previous day using jquery or momentjs.
Use moment().format("h:mm:ss") that returns time in a h:mm:ss format.
var midnight = "0:00:00";
var now = null;
setInterval(function () {
now = moment().format("H:mm:ss");
if (now === midnight) {
alert("Hi");
}
$("#time").text(now);
}, 1000);
JSFIDDLE
A better way would be to compute the seconds until midnight. This is very simple and human readable using MomentJS:
// returns the number of seconds until next midnight
moment("24:00:00", "hh:mm:ss").diff(moment(), 'seconds');
So, just do:
setTimeout(
midnightTask,
moment("24:00:00", "hh:mm:ss").diff(moment(), 'seconds')
);
function midnightTask() {
/* do something */
}
JSFIDDLE
There's only really two ways to accomplish this
poll every x seconds and see whether we're within x seconds of midnight
Calculate the time between now and midnight, and sleep for that amount of time before executing
(1) has been demonstrated in other answers, here's (2).
The first thing to do is calculate the number of milliseconds until midnight then use that as a parameter to javascripts setTimeout.
setTimeout(function(){
// whatever you want to do at midnight
}, msToMidnight);
After you've finished your work in that function, you might want to recaculate the time until next midnight and repeat the process.
So I think you're going about this the wrong way. What you're looking for isn't when it's midnight, you just want to know when the day has changed, which is a much simpler task.
The first thing I'm going to say is avoid using timers at all costs. They're not worth it. The performance hit and extra CPU time you take from running the same function >3600 times a day is ridiculous, especially when it's running on someone else's computer. You don't know how much it can handle, so assume it can't handle much at all. Go easy on your users.
I would suggest listening to a user input event, assuming that this is something you would have on a regular computer, and not something like this, where there is no user input.
If user input events are something you could rely on, I would do this..
var today = new Date(), lastUpdate;
window.addEventListener( "mousemove", function () {
var time = new Date();
// If we haven't checked yet, or if it's been more than 30 seconds since the last check
if ( !lastUpdate || ( time.getTime() - lastUpdate.getTime() ) > 30000 ) {
// Set the last time we checked, and then check if the date has changed.
lastUpdate = time
if ( time.getDate() !== today.getDate() ) {
// If the date has changed, set the date to the new date, and refresh stuff.
today = time
this_is_where_you_would_reset_stuff()
}
}
} )
If you absolutely need to use a timer, then I would do this..
function init() {
var today = new Date();
var midnight = new Date();
midnight.setDate( today.getDate() + 1 )
midnight.setHours( 0 )
midnight.setMinutes( 0 )
setTimeout( function () {
// If the date has changed, set the date to the new date, and refresh stuff.
today = time
this_is_where_you_would_reset_stuff()
init()
}, midnight.getTime() - today.getTime() )
}
init()
Keep in mind that the second way is likely to be far less reliable.
Create a date at midnight this morning, add 86400 seconds, and set a timeout for then:
new Date(Date.parse((new Date()).toString().replace(/\d\d:\d\d:\d\d/,'00:00:00')) + 86400 * 1000)
Here's how you'd use it:
var delay_to_midnight = Date.parse((new Date()).toString().replace(/\d\d:\d\d:\d\d/,'00:00:00')) + 86400 * 1000 - Date.now()
var timeoutid = window.setTimeout(function() { alert("It's midnight!"); }, delay_to_midnight);
I would try:
window.setInterval(resetAtMidnight, 1000*5) // every five seconds
function resetAtMidnight() {
var now = new Date();
if(now.getHours() < 1
&& now.getMinutes() < 1
&& now.getSeconds() < 5 ) {
redrawPage();
}
};

How to add one second to a time string with javascript/jquery

I am trying to create a timer with Javascript but I don't know how to add one second to a time string.
Time string: 03:31:15
function updateWorked() {
var time = $("#worked").html();
???
$("#worked").html(wtime);
}
$(document).ready(function() {
setInterval('updateWorked()', 1000);
});
What should I write in "???" to make this work?
Assuming you are using something like PHP to get the time string in the first place, and you can't keep track of the date/time as a number as suggested by Marc B, you can parse the string yourself like this:
var $worked = $("#worked");
var myTime = $worked.html();
var ss = myTime.split(":");
var dt = new Date();
dt.setHours(ss[0]);
dt.setMinutes(ss[1]);
dt.setSeconds(ss[2]);
var dt2 = new Date(dt.valueOf() + 1000);
var ts = dt2.toTimeString().split(" ")[0];
$worked.html(ts);
Edit: Working jsFiddle here of this code.
Here's the code with a timer: jsFiddle
Below is an example on how to add a second to a time string. You can use the date object to print out the string in any format that you would like, in this example i'm just using the build in toTimeString method.
var timeString = "10/09/2012 14:41:08";
// start time
var startTime = new Date(timeString);
// prints 14:41:08 GMT-0400 (EDT)
console.log(startTime.toTimeString())
// add a second to the start time
startTime.setSeconds(startTime.getSeconds() + 1);
// prints 14:41:09 GMT-0400 (EDT)
console.log(startTime.toTimeString())
If you're trying to keep a counter in real time, you should use new Date() to get the time, and then format it:
function updateWorked() {
var time = new Date(),
wtime = formatDate(time);
$("#worked").html(wtime);
}
However, if you're trying to keep a specific time, then you should up-scope a Date object and use that:
var time = new Date(/* your starting time */);
function updateWorked() {
time.setTime(time.getTime()+1000);
var wtime = formatDate(time);
$("#worked").html(wtime);
}
Also, you'd want to add a formatDate function:
function formatDate(date) {
var hours = date.getHours().toString();
if (hours.length < 2) hours = '0'+hours;
var minutes = date.getMinutes().toString();
if (minutes.length < 2) minutes = '0'+minutes;
var seconds = date.getSeconds().toString();
if (seconds.length < 2) seconds = '0'+seconds;
return hours+':'+minutes+':'+seconds;
}
Using mixture of jquery and javascript you can achieve this example.
I tired to achive what you looking for, first created a date object and get all the values of time, minute and second and then replaced the value.
Please have a look at jsfiddle
DEMO
http://jsfiddle.net/saorabhkr/xtrpK/

Detecting changes to system time in JavaScript

How can I write a script to detect when a user changes their system time in JS?
There is no (portable) way to track a variable in JavaScript. Also, date information does not lie in the DOM, so you don't get the possibility of a DOM event being triggered.
The best you can do is to use setInterval to check periodically (every second?). Example:
function timeChanged(delta) {
// Whatever
}
setInterval(function timeChecker() {
var oldTime = timeChecker.oldTime || new Date(),
newTime = new Date(),
timeDiff = newTime - oldTime;
timeChecker.oldTime = newTime;
if (Math.abs(timeDiff) >= 5000) { // Five second leniency
timeChanged(timeDiff);
}
}, 500);
Check in an interval function that the time has not changed too much:
function getTime() {
var d = new Date();
return d.getTime();
}
function checkTime() {
if (Math.abs(getTime() - oldtime) > 2000) { // Changed by more than 2 seconds?
alert("You changed the time!");
}
oldtime = getTime();
}
var oldtime = getTime();
setInterval(checkTime, 1000); // Check every second that the time is not off
Tested on Windows with Opera & FF and works flawlessly.
Don't think there is a solution to what you are asking for but you can get the users timezone offset.
new Date().getTimezoneOffset() * -1
This returns the offset in minutes from GMT. Bare in mind though this does not take DST into consideration.
var last_time = new Date().getTime();
setInterval(function() {
var time = new Date().getTime();
var offset = time - last_time;
if(offset < 0 || offset > 1500) {
// Time has been changed
}
last_time = time;
}, 1000);
In theory, this should work. It will check every second to make sure the time hasn't been changed. Note that I use 1100 milliseconds as most JS interpreters don't fire off events at exactly the time specified.
Hope this helps!
use performance.now() to get duration, which will be independent of system clock
see https://developer.mozilla.org/en-US/docs/Web/API/Performance/now
var t0 = performance.now();
doSomething();
var t1 = performance.now();
console.log("Call to doSomething took " + (t1 - t0) + " milliseconds.");
And then you can compare performance.now() elapsed with Date.now() elapsed to see whether they are diff too much.
Do you mean if they are changing their own system time to something that is wrong? You can ask the user for their time zone and get the correct time from the server, and then compare it to the user's system time.
You could check every 30 seconds, etc. If the new Time is off by more than 30 seconds +/- some threshold, you could do a more exhaustive comparison to determine how much it has been changed.

Categories

Resources