JavaScript - formatting date with current timezone - javascript

I am using the moment.js library. I have dates in this format: "2014-06-19T18:00:00+02:00" (string). I want to display the date formatted with the user's timezone.
moment.js docs specifies to use moment("2014-06-19T18:00:00+02:00").utc().format()
My questions are:
How can I set the timezone once and not have to put .utc() every time?
How can I test the timezone functionality? Should I change my computer's clock?

Calling .utc() would actually translate the value you put in to UTC. If you want the user's local time zone, then you should just omit that and call .format().
That you passed a +02:00 offset with the original value doesn't matter. By default, moment will adjust the value to the user's time zone.
On the other hand, if you want to keep the offset you provided, regardless of the user's time zone, then you can use the parseZone function.

Related

Date Picker get Date in given timezone instead of local time

In my react application, when i creating a new date object for date-picker using moment-timezone package(with different timezone), the time is automatically converting to the local system time + the chosen timezone time.
Is there any way to create a new date object with set a timezone on client side?
i am using moment-timezone for globalization and Meteor Js for back-end
If I understand correctly, your issue is that you want to provide a Date Picker UI that automatically generates a Date object from the selected date and user time zone setting (retrieved from your database), but what you get is a date in user's local time (hence may already have some timezone offset) + the user time zone offset setting.
You have mainly 3 possible solutions:
Have the Date Picker UI always provide a date in UTC (typically at midnight UTC), then add your user's timezone offset setting.
Have the Date Picker UI take your user's timezone setting as a configuration, so that when it automatically generates a Date, it uses that timezone offset configuration.
Have the Date Picker UI provide a Date in the browser local time, then shift it to UTC, then add your user's timezone offset setting.
Option 1 DatePicker in UTC: I have not seen any library that provides such option, but it does not sound too weird, so you may find one that does. Or you may fiddle with the component code... which is probably overkill compared to option 3.
Option 2 DatePicker with timezone configuration: from your comment, this sounds like what you expect. Unfortunately, I have not seen any library that offers such feature either. As this sounds even more specific than option 1, it is unlikely you can find such a library.
Option 3 local time shift to UTC then add user timezone: this is the standard practice to achieve the objective of generating a Date in a given timezone, starting from a Date in local time, due to all DatePicker UI working just with local time to simplify things. As to shift local time to UTC, you should have plenty questions and answers on SO already.
In case you have to provide an initial value to your Date Picker UI (typically a previous value from database), then make sure to perform the reverse operation, i.e. subtract your user's timezone offset setting to get a date in UTC, then shift to browser locale time. I have seen applications that neglect this part and have incorrect date when the local time has a negative offset to UTC.

sending javascript date object to server without adjusting for time zone difference

Is there a way to send data from the client to a server without adjusting the time to account for the time zone difference between the client and server?
I have an angular app with a nodejs server. When I send a date from a form to the server via an HTTP request and log the date on the server, the date changes to the time in the time zone of the server.
I'd like to send the date object back and forth without it changing.
I always use http://momentjs.com/ when dealing with javascript dates. When a date object is created the systems timezone is used, so you'll always have to adjust for the offset. The easiest solution is to do one of the following
use a string and parse it
use moment().format() with a custom format
use UTC on the client and server
use ticks or unix epoch
There really isn't a great solution, you just need to be consistent.
Use milliseconds .
let now = new Date();
let time = now.getTime();
time contains number of milliseconds in UTC timezone always. In the server you can convert milliseconds to date . This way you dont need to worry about timezones.
According to MDN Javascript Date objects are constructed using UTC.
You can send the date object back and forth without ever changing it, it will simply be interpreted relative to the 'locale' of wherever it is being used.
If you'd like to maintain the local date and time irrespective of location (between different client and server locations) you'll probably need to pass along the locale of the Date as well as the Date itself.
A way to do this is to format your Date as a string in ISO 8601 format with a time offset (like +0100.)
That way you'll get both the local time and the offset used for every time.
You can construct it by hand using the Date.prototoype.toISOString method but that will still be relative to UTC.
Here's another Stack Overflow question on how to get the correct offset yourself.

Initialize a Moment with the timezone offset that I created it with

I'm using moment and moment-timezone in javascript, and this part of it is one of the most unintuitive API's I've ever seen.
I would expect that:
moment("2015-12-14T04:00:00Z").utcOffset()
would be a pure function and return the offset included in the argument, which is 0. But instead it implicitly converts it to my local timezone offset (PST), so this returns -480 Why?? I asked what offset the object i just created has, not what offset I'm currently in. It would be like if I wrote an api where calling User.find(123).name() returns your name instead of the name of user 123.
Anyway, I can do
moment("2015-12-14T04:00:00Z").tz("utc").utcOffset()
But my datetime string is dynamic, so I don't know the timezone.
How can I get the behavior I expected, a Moment in js that is in the timezone offset included in the string i passed in?
Use parseZone to keep the offset as it was passed in.
moment.parseZone("2015-12-14T04:00:00Z")
As to the "why?" part of your question:
moment(...) is local mode. Ambiguous input (without offset) is assumed to be local time. Unambiguous input (with offset) is adjusted to local time.
moment.utc(...) is utc mode. Ambiguous input is assumed to be UTC. Unambiguous input is adjusted to UTC.
moment.parseZone() keep the input zone passed in. If the input is ambiguous, it is the same as local mode.
moment.tz(...) with the moment-timezone plugin can parse input in a specific time zone.
Keep in mind that moment has to contend with a wide variety of inputs.
Also keep in mind that a time zone and a time zone offset are two different things. An offset of -08:00 doesn't necessarily mean you are in the US Pacific time zone.

Moment js utc() time in london - BST

I'm using momentjs lib to updated text on some ajax action. What I need to do is to set a current date & time in london. I'm using moment.utc() function but because of the summer time I'm one hour out.
For example running this on 14:26
console.log( moment.utc().format('HH:mm:ss') );
I'm getting 13:26:53.
Any idea on how to fix this?
Can you use momentJS timezone?
moment().tz('Europe/London');
EDIT: In case you try to use this without seeing the link, it's a separate library you have to include.
If you want the local time instead of the UTC time, just use moment() instead of moment.utc(). You're specifically asking for UTC, so you shouldn't be surprised when you get UTC :)
From the documentation:
By default, moment parses and displays in local time.
If you want to parse or display a moment in UTC, you can use moment.utc() instead of moment().
This brings us to an interesting feature of Moment.js. UTC mode.
While in UTC mode, all display methods will display in UTC time instead of local time.
This is assuming you always want the user's local time. If you want a specific time zone (London) which may not be the user's time zone and isn't UTC, then you should use the library indicated by Takuya's answer. I would think carefully before doing so though - while it may be a sensible approach, you should at least validate that first. It's often reasonable to display a time for user U1 in the time zone of user U2 - but here you're using a fixed time zone. That's only appropriate if you know that U2 will always be in London. It would be really confusing if actually U2 is in some other zone - either the same as or different to U1.

Is there a simple time to get a timezone from a given time?

I need to get a timezone from a time, date is not important, but daylight savings is.
something like:
timezone = function("15:00");
Is there a simple way to do this?
I dont think you can get the timezone from the time but you might get some help from Date.prototype.getTimezoneOffset()
The getTimezoneOffset() method returns the time-zone offset from UTC,
in minutes, for the current locale.
Example:
var x = new Date();
var currentTimeZoneOffsetInHours = x.getTimezoneOffset() / 60;
No, of course not. Think about it, you're passing 15:00 to that function, presumable denoting it's 3PM. But in what timezone is it 3 PM? No way of knowing. It's like me saying it's quarter to, without saying what hour it's quarter to to.
The only way you can get a timezone in JS is by using the Date object, but that just shows the timezone of the machine on which your code is running, nothing about the TZ that "created" the time you're processing.
Also note that daylight saving isn't a global phenomenon, quite the contrary. AFAIKT, there isn't a single time-zone where DST has always been in place...
In order to get TimeZone information you need more than a Date (and an offset). You need a location.
Javascript does not know the location that it resides in but it does know the current offset from UTC. That is different than a Time Zone. The daylight savings time issue play havoc with this key difference.
This has posed problems when dealing with server applications that know their timezone and report dates as being in a specific Time Zone.
My rule of thumb has been fairly simple in this regard.
Always use Long or long (a 64 bit number) to store, pass and process dates times or intervals, only convert to Date, Calendar or DateTime objects when interacting with people.
Once you have a date object, such as with new Date(), you can use .getTimezoneOffset() to get the number of minutes between the date's object and UTC, which is timezone information you can use.

Categories

Resources