0

I am using firebase toDate()-method to get a Date object from my timestamp:

myTimestamp.toDate()

This creates a Date-object (which I need), but in local time (the time my operating system uses). How can I get it to give me a Date-Object in CEST/CET?

edit: The timestamp comes from firebase and I am using their toDate() method.

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
progNewbie
  • 4,362
  • 9
  • 48
  • 107
  • Of what type is `myTimestamp`? AFAIK there is no built-in object in JavaScript itself that exposes a `toDate` method. Also, `Date` objects are always in local time -- see [Get date time for a specific time zone using JavaScript](//stackoverflow.com/q/11124322) for how to convert. – Heretic Monkey Sep 05 '18 at 00:16
  • @HereticMonkey—[*Date objects*](http://ecma-international.org/ecma-262/9.0/#sec-date-objects) are always UTC, they convert to/from local when presenting/parsing strings. – RobG Sep 05 '18 at 01:50
  • Duplicate of [*Convert date to another timezone in JavaScript*](https://stackoverflow.com/questions/10087819/convert-date-to-another-timezone-in-javascript?s=1|192.4542)? – RobG Sep 05 '18 at 05:00

1 Answers1

2

The integer value contained by a Date object (milliseconds since unix epoch) is not affected by timezones. It represents the same point in time for all people on the planet.

However, when you print a Date object, you will see the date rendered with local timezone. If you want just that integer number inside the Date, call getTime() on it for use elsewhere.

You can feed a Date (or the underlying number) to other libraries that may do what you really want with the date, including momentjs with moment-timezone. For example, this may work with moment:

moment(your_date).tz('Desired Timezone').format('ha z')
Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
  • Without a library there is `new Date().toLocaleString('de',{timeZone: 'Europe/Berlin', timeZoneName:'short'})` but support for [IANA timezone names](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones) is fairly new. ;-) – RobG Sep 05 '18 at 01:57
  • @RobG somehow this line of code doesn't change my date object at all. What could I be doing wrong? – progNewbie Sep 05 '18 at 10:14
  • 1
    @progNewbie—it may be that the host doesn't support the *timeZone* option, see the [*MDN compatibility chart*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString#Browser_compatibility). It seems to work in the most recent Chrome, Firefox and Safari and produces "6.9.2018, 02:48:44 MESZ". Using en-GB and Chile/EasterIsland produces "05/09/2018, 19:48:44 GMT-5" in Firefox and Safari, but Chrome throws a range error, it doesn't support that timezone name. – RobG Sep 06 '18 at 00:55
  • Firebase functions support timezone but unfortunately not the first parameter to do with localization. – user37309 Aug 15 '19 at 02:47