Firebase toDate() use CEST instead of localTime
Firebase toDate() use CEST instead of localTime
I am using firebase toDate()
-method to get a Date object from my timestamp:
toDate()
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?
Date
Date
edit:
The timestamp comes from firebase and I am using their toDate()
method.
toDate()
myTimestamp
toDate
Date
@HereticMonkey—Date objects are always UTC, they convert to/from local when presenting/parsing strings.
– RobG
Sep 5 '18 at 1:50
Duplicate of Convert date to another timezone in JavaScript?
– RobG
Sep 5 '18 at 5:00
1 Answer
1
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')
Without a library there is
new Date().toLocaleString('de',timeZone: 'Europe/Berlin', timeZoneName:'short')
but support for IANA timezone names is fairly new. ;-)– RobG
Sep 5 '18 at 1:57
new Date().toLocaleString('de',timeZone: 'Europe/Berlin', timeZoneName:'short')
@RobG somehow this line of code doesn't change my date object at all. What could I be doing wrong?
– progNewbie
Sep 5 '18 at 10:14
@progNewbie—it may be that the host doesn't support the timeZone option, see the MDN compatibility chart. 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 6 '18 at 0:55
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Of what type is
myTimestamp
? AFAIK there is no built-in object in JavaScript itself that exposes atoDate
method. Also,Date
objects are always in local time -- see Get date time for a specific time zone using JavaScript for how to convert.– Heretic Monkey
Sep 5 '18 at 0:16