I am working on a clock that count down for my project, and I am curios about where Javascript get date and time from? From internet? From device? From browser?
// Get todays date and time
var now = new Date().getTime();
It gets the current date & time (and by proxy, the UTC offset/locale) from the client's local environment. You can test this by changing your local clock.
You don't need an internet connection to use JavaScript. It gets the current date & time from the client's local environment.
The Date object is a datatype in the JavaScript language. Most methods simply allow you to get and set the year, month, day, hour, minute, second, and millisecond fields of the object, using either local time or UTC (GMT, or universal) time.
The ECMAScript standard requires the Date object to be able to represent any date and time, to millisecond precision, within 100 million days before or after 1/1/1970. This is a range of plus or minus 273,785 years, so JavaScript can represent date and time till the year 275755.
Source
Related
I’m currently working on Timezone related options across my application. I want to change the user’s default timezone which the browser picks during
let date = new Date()
the function returns the date and time with respect to browser zone.
Is there any setting which I can edit such that across the application, different zone is used?
Using moment-timezone, I can work on this dynamically. But I am using few packages that are using Javascript Dates.
Therefore, is there a setting or a parameter through which we can change the zone of the browser and whenever the new Date() function is called, the time fetched is in that timezone?
A Date object does not actually store a time zone. It simply stores the number of milliseconds since since Jan 1, 1970 00:00 UTC, otherwise known as the "UNIX Epoch".
The methods of Date give the illusion of having a stored time zone because, when you call a method like getHours(), the system reports the time in minutes in the time zone of the user.
But what's happening under the hood is something like this:
// Stores the number of milliseconds since 1970-01-01T00:00:00 UTC.
// Does NOT store the current time zone.
const date = new Date();
// This returns the number stored above
const msecsSinceEpoch = date.getTime();
// This returns the current UTC offset of the user's time zone.
// For example, if the user's OS settings use the time zone in
// California in December 2022, then this method will return 480.
// If you subtract that number of minutes from the current UTC time,
// then it will equal the local time in California in December 2022.
const offsetMinutes = date.getTimezoneOffset();
// When you call methods like .hours(), the browser uses the two
// values above to calculate the result. Like this:
const MSECS_PER_MINUTE = 60*1000;
const MSECS_PER_HOUR = MSECS_PER_MINUTE * 60;
const offsetMsecs = offsetMinutes * MSECS_PER_MINUTE;
const totalHours = Math.trunc ((msecsSinceEpoch - offsetMsecs) / MSECS_PER_HOUR);
const hours = totalHours % 24;
// The code above will return the same result as this:
const hours2 = date.getHours();
The code above should make it clear why you cannot change the time zone of a Date object: because the Date object doesn't store a time zone at all! There's no time zone to change. And, for security reasons, code running in the browser can't change the user's OS settings to change the time zone.
So your first idea (to change the time zone of Date) won't work. But many web apps allow viewing date and time information in different time zones.
Soon (likely sometime in 2023) JavaScript will be adding a new built-in object called Temporal that will make it easier to work with time zones. In the meantime, it's straightforward to use different time zones using libraries like moment-timezone, or you can use one of the Temporal polyfills.
But that won't help you in the specific case you're asking about: how can you change the time zone of a library that only accepts a Date parameter. Some libraries provide a way to change the time zone of data displayed. Others do not, and those that don't provide a way to change the time zone come in two types:
Libraries that don't care about time zone at all. For example, a library that schedules a reminder text message in 60 minutes doesn't care about the time zone. It only cares about the exact time: the value stored in a Date and returned by .getTime(). If your library is like this, then you should be fine passing a Date and don't need to worry about time zones.
Libraries that show data to users in a specific time zone. For example, a date picker or a calendar. These libraries typically use the time zone in the user's OS settings. However, many libraries provide a way to override that time zone. You'll need to check your libraries' documentation or search questions about how to set the time zone for the output of those libraries. Or you can switch libraries!
I wanted to know if a date object created at any point of time differ based on time zones or not. I tried this by executing new Date().getTime() once for IST and immediately again by setting my PC time zone to GMT. The resultant values are:
IST - 1633334780053
GMT - 1633334788831
A difference of around 8000 milliseconds
From this it seems that datetime objects created at same moment are exactly same no matter in which time zone they are created. Please suggest if this understanding is correct or is there more to it.
You're right. Two different date time objects created at the same point of time are same no matter the time zone.
They can be formatted to their corresponding timezone representation using javascript.
One important thing to be noted is that the date time object created uses the system's date time configuration to find the correct time. If the system's date and time configurations are correct and in sync, then the date time object created in the browser will be correct and will match the system time at the time of creating that object.
This is detailed in the JavaScript specification: https://tc39.es/ecma262/#sec-date-objects.
More information is in the MDN docs Date.getTime():
The getTime() method returns the number of milliseconds* since the Unix Epoch.
*JavaScript uses milliseconds as the unit of measurement, whereas Unix Time is in seconds.
getTime() always uses UTC for time representation. For example, a client browser in one timezone, getTime() will be the same as a client browser in any other timezone.
So new Date().getTime() will always return the number of milliseconds since 1970-01-01 00:00:00 UTC, regardless of the client / machine timezone setting.
My scenario is a Date object created using the browser timezone (just using new Date()) and sent to the server, but I want to send this date with another specific timezone let's assume it's, Europe/Athens.
What would be the best representation of the actual date string so I can convert it back to a Date object in the backend in the actual Europe/Athens date?
I have the timezone info but not sure how to get a Fri Feb 05 2021 05:30:00 GMT-0500 (Eastern Standard Time) and convert it to Europe/Athens date.
I have tried to use date-fns but didn't get far.
You've got a few different questions and misconceptions, so I will attempt to address each of them, starting with question in the title:
How to convert a Date in specific Timezone and send to server
If you mean a date like 2021-01-18, that cannot be in a particular time zone. It is, by definition, just a date. Think about a printed calendar you might hang on your wall that has a square for each date. There are no time zones associated with such calendars. One can ask "what date is it now in a particular time zone", but the answer itself has no time zone.
If instead you meant a JavaScript Date object, the answer is again "you can't". The Date object is not actually a date, nor does it have a time zone, but rather it is a timestamp. Internally, a Date object only holds one value - the number of milliseconds that have elapsed since 1970-01-01 00:00:00.000 UTC (not considering leap seconds). It has no time zone. Instead, some functions such as .toString() will apply the system-local time zone while operating. That time zone comes from the operating system (in most cases). It is not stored inside the Date object itself.
My scenario is a Date object created using the browser timezone (just using new Date()) ...
That will use the system clock where the browser is running, but the time zone is not relevant. The Date object will be constructed from the Unix timestamp that represents "now". Such timestamps are inherently UTC based. The browser fetches the UTC time directly from the operating system, without considering time zone.
... and sent to the server
One cannot send an object to a server without going through deserialization on one side and serialization on the other.
... but I want to send this date with another specific timezone let's assume it's, Europe/Athens.
What would be the best representation of the actual date string so I can convert it back to a Date object in the backend in the actual Europe/Athens date?
Since the object only represents "now", you don't need to send it in a time zone specific format. Just send the UTC time. The ideal format is ISO 8601, which can be obtained directly using the .toISOString() function from the Date object.
Depending on your use case, you might also consider whether you might instead just take the UTC time from the server instead. At least you will have some control over the clock.
On the server side, if you need the time in a specific time zone, then convert from UTC to that time zone on the server, not on the client.
Also, from comments:
I believe even EPOCH is different between timezones. I could just get the EPOCh and then try to work with converting to specific timezones.
That is incorrect on a few levels. First, understand that epoch is just an English word meaning essentially "a representation of a starting point". It isn't a format, nor is it an acronym. In JavaScript, Date objects use Unix timestamps, which use an epoch of 1970-01-01T00:00:00.000Z. In other words, Midnight Jan 1st 1970 UTC is the 0 timestamp. Sometimes, such timestamps are referred to as "epoch time". That's a misnomer in my opinion, but even still - they are always UTC based. There is no time zone, and thus they are the same for the whole world.
Try to use toLocaleString:
let date = (new Date()).toLocaleString("en-US", {timeZone: "Europe/Athens"});
My app is based on XULRUNNER. I found when I fetch the current timestamp with Date.prototype.getTime, It seems give me the GMT time not the time of my time zone. But in firefox, there is no such a problem. I am confused that is there a way to set the time zone in xulrunner with JS.
Date.prototype.getTime doesn't really have a notion of UTC or timezone, it's a number of milliseconds elapsed since a specific point in time, the Unix EPOCH, which happens to be defined in UTC. If you convert it to a date manually, you will always get a value seemingly in UTC, in XULRunner or Firefox.
You need to use the other methods on Date objects to retrieve the time in the local timezone.
var now = new Date();
console.log(now.getTime()); // 1390141979617
console.log(now.getUTCHours()); // 14
console.log(now.getHours()); // 9
Compare the results of toString() and toLocaleString()
I typed "date" in console...and I get Tue Sep 20 01:01:49 PDT 2011 ...which is correct.
But then I do this in node.js, and I get the wrong time.
var ts = String(Math.round(new Date().getTime() / 1000));
Output is: 1316505706, which is an hour behind.
#KARASZI is absolutely correct about the root cause: Unix timestamps are always UTC unless you manipulate them. I would suggest that if you want a Unix timestamp you should leave it in UTC, and only convert to local time if you need to display a formatted time to the user.
The first benefit of doing this is that all your servers can "speak" the same time. For instance, if you've deployed servers to Amazon EC2 US East and Amazon EC2 US West and they share a common database, you can use UTC timestamps in your database and on your servers without worrying about timezone conversions every time. This is a great reason to use UTC timestamps, but it might not apply to you.
The second benefit of this is that you can measure things in terms of elapsed time without having to worry about daylight savings time (or timezones either, in case you're measuring time on a platform which is moving!). This doesn't come up very much, but if you had a situation where something took negative time because the local time "fell back" an hour while you were measuring, you'd be very confused!
The third reason I can think of is very minor, but some performance geeks would really appreciate it: you can get the raw UTC timestamp without allocating a new Date object each time, by using the Date class's "now" function.
var ts = Date.now() / 1000;
The reason is that the getTime function returns the time in the UTC timezone:
The value returned by the getTime method is the number of milliseconds since 1 January 1970 00:00:00 UTC. You can use this method to help assign a date and time to another Date object.
If you want to fetch the UNIX timestamp in you current timezone, you can use the getTimezoneOffset method:
var date = new Date();
var ts = String(Math.round(date.getTime() / 1000) + date.getTimezoneOffset() * 60);
Note you can avoid this confusion by using a node.js package like timezonecomplete or timezone-js which have an interface that is much less error-prone for date and time manipulation.
date in console will return the server time, whereas using JavaScript on a webpage will return the client's local time.