3

When I execute

myDate = new Date('2000-02-02 12:30:00')

I get a date object like this 2000-02-02T11:30:00.000Z because there is a difference of one hour between my timezone (Europe/Vienna) and UTC.

I can now change the hour by doing

myDate.setHours(10)

and the result will be a date object like this 2000-02-02T09:30:00.000Z because of the one hour difference.

I can also set the UTC hours by

myDate.setUTCHours(10)

to get a dateobject like this 2000-02-02T10:30:00.000Z


I'm looking for something similar to

myDate.setLocaleHours(10, "America/New_York")

(which doesn't exist)

What is the best way to set the hours to a specific value in a timezone which is not my current one and also not UTC?

Zauz
  • 299
  • 2
  • 11
  • moment.js timezone plugin would be a help here – charlietfl Nov 08 '18 at 11:36
  • Thanks, I have heard of it but it's my last resort because I would like to have a solution without dependencies. – Zauz Nov 08 '18 at 11:39
  • Then perhaps you are better off looking for an API source that can give you the current offset for a specific timezone to use in `setHours`. Issues like daylight savings time make it complex – charlietfl Nov 08 '18 at 11:44
  • Possible duplicate of [Create a Date with a set timezone without using a string representation](https://stackoverflow.com/questions/439630/create-a-date-with-a-set-timezone-without-using-a-string-representation) – ponury-kostek Nov 08 '18 at 12:27
  • "2000-02-02 12:30:00" is not a format supported by ECMA-262 so paring is implementation dependent. It results in an invalid Date in at least one current browser. You might consider the *timeZone* option of [*toLocaleString*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString#Examples). – RobG Nov 08 '18 at 20:21

1 Answers1

1

How can I setLocaleHours() on a date object?

What is the best way to set the hours to a specific value in a timezone which is not my current one and also not UTC?

You can't. At least, not on the Date object. It has no ability to set time based on an arbitrary time zone.

There is work in progress to rectify this, by adding a new set of standard objects to ECMAScript. See the TC39 Temporal proposal for more details. The temporal ZonedInstant will have functionality to work with named time zones.

However, for now, you will need a library that understands time zones. Moment-timezone is one option, though, these days the Moment team recommends Luxon for modern app development. Another great option is js-Joda.

Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575
  • It's slightly awkward in Luxon because the setters always use the DateTime's zone, so you need something like `dt.setZone("America/New_York").set({ hours: 10 }).setZone("local")` – snickersnack Nov 11 '18 at 16:31