I have been writing some JavaScript code that relies upon universal time. I have been doing this online with two computers. One of which is 24 minutes behind the other.
Example:
Computer 1: 25/07/2020, 21:57 Computer 2: 25/07/2020, 22:21
When both computers enter a UTC number they are still the equivalent of 24 minutes apart.
Computer 1: 1595710054892 Computer 2: 1595711497605
This difference in time is causing problems with my programme as it relies upon timed notifications.
Is there anyway to correct for this or will I just have to hope that computers that use my JavaScript code will all have the same time within their respective timezone?
If you can't trust the clock on the computer (which is, frankly, shocking for a network-connected system in 2020) then you need to get the current time from somewhere else.
The standard way to do this would be to use the Network Time Protocol.
A quick Google turns up this JavaScript implementation of an NTP client:
var ntpClient = require('ntp-client');
ntpClient.getNetworkTime("pool.ntp.org", 123, function(err, date) {
if(err) {
console.error(err);
return;
}
console.log("Current time : ");
console.log(date); // Mon Jul 08 2013 21:31:31 GMT+0200 (Paris, Madrid (heure d’été))
});
If you're dealing with JS in a browser, you won't be able to use the NTP protocol directly so you would need to proxy the request via some server-side code which would lose some accuracy (but assuming a reasonable network connection, that would be in the order of a few seconds rather than 10s of minutes).
Related
I am new to Youtrack Workflow. I am trying to create a new workflow for which I require hours from the current date-time.
I am using new Date().getHours() but it's not returning proper value.
say for example my current time is Fri Jun 12 2020 18:29:29 GMT+0530 (India Standard Time) then it should have got 18 as the current hour but, I am getting 12 as the current hour.
Also in the date-time function in Youtrack, there is no option for the same (https://www.jetbrains.com/help/youtrack/incloud/v1-date-time.html)
Please help me with this.
As of now, new Date().getHours( returns the time from the server Youtrack runs on. For example, if you run it on your own server (Standalone version), it returns the time set in your server's OS. If you run it on a Youtrack server (Incloud version), it returns the time set in our server's OS. If the server's OS fails to return the time, we fall back to the UTC time.
That's not a transparent behavior and is going to be addressed in this task in: https://youtrack.jetbrains.com/issue/JT-57972 In this task, we want to change it so that the time is returned based on your Youtrack settings. You can watch the issue to get notified of the changes made there. How to do it: https://take.ms/L0k8g (screenshot).
For now, though, if you use your own server, you can try to change the time there. Otherwise, I suggest that you get time in UTC using Date.getUTCHours() and then add constant hours to get your local time.
So a little context, I have an array of 24 arrays -- one for every hour in the day.
So midnight, 0 index, would be [133.00, 234.00] which would indicate 133 actions from 12 - 1230 and 234 actions between 1230 - 1am.
I need to adjust these indexed arrays to account for the user's timezone in a browser with JS, so that if the user is in New York the 0 index (midnight in the user's home turf) is displayed in China's offset (12pm tomorrow, from user's perspective).
I've been trying to think of a solution, I have a simple function for what I've been able to think of
function offsetHourIndex(hourIndex, dataCenterTimeZone) {
let userTime = new Date().setHour(hourIndex)
return moment(userTime).tz(dataCenterTimeZone).hour();
}
How reliable would this approach be?
Your approach has a few problems:
You are assuming that the current date in the local time zone is the correct date for the target time zone. Most of the time, there are two dates active somewhere around the world. For example, 2019-04-02 04:00 in London is 2019-04-01 23:00 in New York. If you just take hour 4 from London but apply it to the current date in New York, you've created a whole new point in time, a day too early.
You assume there will be exactly 24 hours in every day. In time zones that have transitions for daylight saving time or changes in standard time, you may have more or less hours of local time on a the day of the transition.
In the case of a backward transition, there is a period of ambiguous local time. For example, when US Pacific Time moves from PDT to PST in November, the hour from 1:00-1:59 is repeated. If data from both hours are summarized into array element 1, then you will have higher than normal results for that hour. The opposite is true for forward transitions - you will have an hour with no data.
The time zone setting of the server can be a fickle thing. What if you change data centers? What if you move to the cloud? What if you are operating multiple data centers? What if a server administrator thinks all they are affecting by changing the system time zone is the readout on the taskbar or front panel, etc., and then it affects your application? In general one should avoid these things by never relying on the server's local time zone setting.
You can avoid all of these problems by basing everything on Coordinated Universal Time (UTC) - especially the array. Then you can be ignorant of any server time zone setting, and just base everything off the current UTC day, which is the same all over the world.
This will give you the local hour from the given UTC hour in your index:
var localHour = moment.utc({hour: hourIndex}).local().hour();
You do not need moment-timezone for the above recommendation.
However, if you really feel like you need to convert from a specific time zone to the browser local time, then you would use moment-timezone like this:
var localHour = moment.tz({hour: hourIndex}, timeZoneName).local().hour();
Note when you do this, you also have another problem - not every time zone is offset by a whole number of hours. For example, India uses UTC+05:30. There are many that are :30 and a few that are :45. By tracking hours only, you're not providing enough information to properly convert to the correct local hour. Your results may be off by one.
It seems reasonable. And the code should work as long as you have the properly formatted inputs. I like the brevity and clarity of the function. Any reason you are concerned about reliability?
You might mention in your question that you are using the moment and moment-timezone packages here to derive your data via its functions (moment & tz) on this line of code:
return moment(userTime).tz(dataCenterTimeZone).hour();
Your function may appear a bit cryptic without the imports in your example for folks reading here to understand, such as :
import * as moment from 'moment';
import 'moment-timezone';
I want Client timezone name (e.g. India Standard Time) in ASP.Net MVC Application.
So, I Can use TimeZoneInfo.FindSystemTimeZoneById(TimeZoneName) function.
I have tried with new Date().getTimezoneOffset() (reference)
But, there is problem with Daylight Saving Time in this Code.
In javascript, i have also tried with new Date().toString()
But, this gives result in different format with different browser.
In firefox, chrome & safari,
Answer is "Tue May 08 2012 14:00:00 GMT+0530 (India Standard Time)"
In IE8, it is "Tue May 8 14:00:00 UTC+0530 2012"
Similar problem with opera also.
So, this method will not work for IE & Opera.
What will be best way to identify Client TimeZone?
the best and the most utilized way is to identify clients location thru some 3rd party library and database utilizing the ip of the client.. and then based upon the location of the client decide the timezone
Do you need to know the timezone or just the offset from UTC? Because timezones are not an ISO standard and can be changed almost arbitrarily, I prefer to work with the client's offset from UTC and I always get it from the client at login time or whenever they submit a form on which I need the client time. Sometimes I work out the GTM offset of the client and persist it to use wherever I display or use a time.
So I have a global JavaScript function like this which returns the given local date as a universal string:
function aspClientDateTime(dateObject) {
return dateObject.getFullYear() + '-'
+ this.leadingZero((dateObject.getMonth() + 1), 2) + '-'
+ this.leadingZero(dateObject.getDate(), 2) + ' '
+ this.leadingZero(dateObject.getHours(), 2) + ':'
+ this.leadingZero(dateObject.getMinutes(), 2) + ':'
+ this.leadingZero(dateObject.getSeconds(), 2);
}
On form submit, I get the current client date and store it in the form:
myForm.clientTime.val(aspClientDateTime(new Date()));
You then know what time it is in the browser and you can work out UTC offsets etc on the server.
The problem with timezones is that any government could introduce a new one tomorrow, as Samoa recently did. Typically I want to know what the offset of the user is right now, not what timezone they are in.
If it is the latter you really need, you might have to ask them, in the same way that Skype does it.
There is a library for detecting the timezone through JavaScript. It'll give you the name of a good enough timezone. It does not do geolocation or ip-lookup so it is very fast, but it is not extremely exact. For example it'll return "Europe/Berlin" for anyone in the Central European Timezone. It should be good enough for server side datetime normalizations however.
https://bitbucket.org/pellepim/jstimezonedetect
What is the best way to synchronise the time on a webpage with the server?
My webpage needs to start a countdown at the same time for all users, and and end at exactly the same time to prevent any one user having a slight time advantage.
My problem is similar to this question but the accepted answer helps but does not fully answer my concerns: how-to-sync-a-javascript-countdown-with-server-time
I use Ajax after pageload to get the server time, but am I guaranteed over 15 minutes that the countdown will end at exactly the same time for each client?
Even if the timers accurately measure the time, there could still be a discrepancy of just under 1 second between client pages caused by disregarding the milliseconds for the setInterval - is there any way to overcome this?
The accepted answer is good and helped inspire me as I wrote a library to solve this problem. The library yields more precise answers by looking at the load times of itself, rather than the whole page (as done with performance.timing above) and then gets even better precision by following with a series of 10 XMLHttpRequests. Also, addressing your second concern, my library doesn't disregard the milliseconds (as does the accepted answer).
The library is called ServerDate and is freely available.
Here's part of the README:
You can use ServerDate as you would use the Date function or one of its
instances, e.g.:
> ServerDate()
"Mon Aug 13 2012 20:26:34 GMT-0300 (ART)"
> ServerDate.now()
1344900478753
> ServerDate.getMilliseconds()
22
There is also a new method to get the precision of ServerDate's estimate of the
server's clock (in milliseconds):
> ServerDate.toLocaleString() + " ± " + ServerDate.getPrecision() + " ms"
"Tue Aug 14 01:01:49 2012 ± 108 ms"
You can see the difference between the server's clock and the browsers clock, in milliseconds:
> ServerDate - new Date()
39
In modern browsers, you can achieve this by assigning a timestamp to a JavaScript variable, and use the Performance object to calculate the exact time.
Example:
var tsp = new Date('Sun Feb 19 2012 17:55:14 GMT+0100 (CET)'); // "Timestamp"
window.onload = function() {
var performance = window.performance || window.mozPerformance || window.msPerformance || window.webkitPerformance || {};
tsp.setTime(tsp.getTime() + performance.timing.loadEventStart - performance.timing.navigationStart
// after window.onload, you're sync with the server
// Example of timer:
setInterval(function() {
tsp.setSeconds(tsp.getSeconds() + 1);
document.title = tsp.toString();
}, 1000); // 1000 ms = timer may be off by 500ms.
};
For more information on this object, have a look at the MDN's article.
A demo is provided here.
Ideally your solution would involve the server sending out the signal that the submit form is open to all clients at the same time. For that you could use web sockets if you have no problem with excluding people with older browsers. There are also fallbacks using long polling for those browsers.
I am not sure how well websockets do together with PHP though.
I've only ever used socket.io together with node JS. With that solution it would be trivial to set a server-side timeout and notify all clients at the same time when it's complete. It automatically detects the browser support and chooses a method that works best for a given browser.
Using this solution the clients will only ever allow submissions when the server has told them it is ready. As long as the server you submit to performs validation you should be fine.
I need to find the time zone of the client machine using ASP.NET (C#) or JavaScript. What are the different time zones that are available all over the world and how to convert the date and time based on the users time zone.
Please provide some suggestions or sample coding to change the time based on the time zone.
You cannot find client time zone settings from ASP.NET.
You can use JavaScript to tell the current time, but there are several time zones that can be synchronized at any given time.
In Chrome, you can get the time zone from the JavaScript date object. There's no specific function for it, from what I've found, but the code
(new Date()).toString()
will yield something like
Mon Apr 18 2011 08:58:59 GMT+0200 (W. Europe Daylight Time)
In websites, the best approach I've found has been to have a setting for each user to specify the time zone to display all times in. If the JavaScript getUtcOffset gives a different offset than what is expected for the user's time zone, I'll show a notice for the user to review their settings. If time zone can be guessed from the date (which I've only found to be the case in chrome), I'll suggest that time zone, but I still resort to a select box for the user to manually pick the time zone.
Even so, it is possible to have the wrong time zone setting, without the script noticing it, because for a great part of the year, the two time zones may be perfectly synchronized.
Once you have a time zone (you can enumerate them all with System.TimeZoneInfo.GetSystemTimeZones()), you can convert UTC dates with System.TimeZoneInfo.ConvertTimeFromUtc and System.TimeZoneInfo.ConverTimeToUtc, respectively.