is javascript new Date() created at same time on 2 diff machines/timezones exactly same? - javascript

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.

Related

Make time independent of browser time zone

i am printing a timestamp in console of chrome browser using following code,
moment("2021-01-12 00:00:00").utc().utcOffset(-new Date().getTimezoneOffset()).format('x')
this line prints the timestamp at given time and date.
if i change timezone from "windows Date and time settings" , the output of above line also changes .
how can i make output of above line constant irrespective of timezone of current browser window ?
The documentation for Date.protoype.getTime() states:
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.
As such the timestamp you get from a Date is always UTC with timezone information taken from the host environment (OS).
By default JavaScript (and moment) will parse dates and times assuming they are in the user's local timezone and therefore affected by changes to Windows date and time settings.
To keep it consistent you need to tell moment to parse the value as UTC.
const timestamp = moment.utc("2021-01-12 00:00:00").format("x");
console.log(timestamp); // prints 1610409600000
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
No matter which timezone you're in, you should get the value 1610409600000 logged to the console.

How to convert a Date in specific Timezone and send to server

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"});

Where Javascript get date, time from?

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

Is it possible to set time zone in xulrunner with JS

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()

How come my javascript (node.js) is giving me the incorrect timestamp?

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.

Categories