0

I would like to know the local timezone a user is in. E.g. knowing that LA is 7 hours behind UTC can I get the time difference of a user from the browser, to test whether the user is in the local (LA) timezone?

I would like to have the following statement on my website

{% if user.timedelta_to_utc == -7 %}

is there a way to get user.timedelta_to_utc? thanks carl

edit: Ok here is my attempt, which failed. I used the moments.js package and did the following

{% if moment(utc_time).calendar() != moment(local_time, local=True).calendar() %}

where utc_time is a timestamp at utc time and local_time is the same timestamp corrected by the time difference between local and utc. So the statement above should be true if I am in a different timezone (The moments package automatically transfers the date to local time except if I give it local=True). It seems that moment objects cannot be compared that way, since the statement above seems to be always true...

carl
  • 4,216
  • 9
  • 55
  • 103

1 Answers1

0

I would like to know the local timezone a user is in. E.g. knowing that LA is 7 hours behind UTC can I get the time difference of a user from the browser, to test whether the user is in the local (LA) timezone?

Los Angeles is in the US Pacific Time zone, which uses UTC-7 only during daylight saving time - otherwise it is in UTC-8. A numerical value cannot represent an entire time zone. It can only represent the offset from UTC for a specific moment in time.

Additionally, many different time zones share the same numerical offset - perhaps at the same time of year, or perhaps at a different time.

So, if you know that a user is in Los Angeles, you can determine that their current time zone offset is either -7 or -8, but given only -7 or -8 you cannot tell the the user is in Los Angeles. It is a one-way, time-specific relationship.

Ok here is my attempt, which failed. I used the moments.js package and did the following

{% if moment(utc_time).calendar() != moment(local_time, local=True).calendar() %}

That is a bit bizarre, as the calendar function returns various human-readable string values, as described here. Trying to compare them for equality doesn't make any sense.

Also, there is no overload of the moment constructor that takes local=True as a second parameter. Local is the default when you just use moment(string). If you want UTC, you'd use moment.utc(string). It doesn't matter whether the string contains a local or utc value - that only controls how the input value is interpreted, not the mode the moment is set to.

If you just want the UTC offset of a specific moment, there are functions for that.

var m = moment();
m.utcOffset() // returns offset in minutes, such as -420
m.format("Z") // returns offset as string, such as "-07:00"

With regard to determining the user's actual time zone, such as America/Los_Angeles, you can refer to this question.

Community
  • 1
  • 1
Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575