0

I have a string in ISO format 2020-03-11T21:00:00Z. I need help with converting this string to a Date object but keep it as UTC timezone. The expected output is Wed Mar 11 2020 21:00:00 GMT+0000 (UTC).

I've tried moment.utc('2020-03-11T21:00:00Z').toDate() but the output was in my local timezone: Thu Mar 12 2020 05:00:00 GMT+0800 (Malaysia Time).

Thanks

user7554295
  • 420
  • 5
  • 11
  • A `java.util.Date` object does not contain timezone information. There is no such thing as "a `Date` object but keep it as UTC timezone". Instead, when you display your `Date` object, you must make sure to format it using the desired timezone. – Jesper Mar 19 '20 at 10:20
  • @Jesper the quesiton is about javascript, and the momentjs library (as per the tags from OP), not java – Pac0 Mar 19 '20 at 10:21
  • 2
    However, the comment from Jesper is somehow relevant. th *display* of the date is dependent on your locale. Internally, there is not timezone associated to the date in javascript either. – Pac0 Mar 19 '20 at 10:23
  • Does this answer your question? [Convert date to another timezone in JavaScript](https://stackoverflow.com/questions/10087819/convert-date-to-another-timezone-in-javascript) – Pac0 Mar 19 '20 at 10:24
  • 2
    Those two times are equivalent. If you want to *format* it again to display in a certain timezone, then do that explicitly. – deceze Mar 19 '20 at 10:27
  • @deceze You mean something like this: `moment.utc('2020-03-11T21:00:00Z').format('LLLL')` ? I've tried but it gives me string, where I needed a Date type – user7554295 Mar 19 '20 at 10:35
  • @Pac0 thanks, will check it out – user7554295 Mar 19 '20 at 10:36
  • @user7554295 about the type : actually, you already have the correct Date object. But when you try to display the output, it uses internally `toString()`, and by default it uses the timezone of your machine to format it, and some options from your browser (if you use a browser). The display you show and expect _are_ strings, so this is really an output format problem. – Pac0 Mar 19 '20 at 10:51
  • Again, the `Date('Thu Mar 12 2020 05:00:00 GMT+0800 (Malaysia Time)')` and `Date('Wed Mar 11 2020 21:00:00 GMT+0000 (UTC)')` are equivalent for all intents and purposes. It *looks* different when you inspect it, but it's the same point in time. Yes, when you format it to a specific timezone like `.format('LLLL')`, then it'll be a string, naturally. – deceze Mar 19 '20 at 11:05

0 Answers0