user2720626
user2720626

Reputation: 49

Moment js showing wrong time when i format

I'm trying to convert java datetime instant to hh:mm format using moment js

moment("2020-03-21T17:34:00Z").utcOffset(-0500).format("hh:mm")

it should give me 12:34, but somehow it is giving "12:14" which is the wrong time.

Upvotes: 1

Views: 1538

Answers (2)

Matt Johnson-Pint
Matt Johnson-Pint

Reputation: 241959

A few things:

  • The utcOffset function behaves differently whether you pass a string or a number. As a number, it's expected to be in terms of minutes. Since you have hours and minutes in your offset, you should pass it as a string: .utcOffset("-0500")

  • Format strings are case sensitive. You should use HH:mm (24-hour time), or hh:mm a (12-hour time). Since you used hh:mm without an a, anything after 12 pm will be misrepresented.

  • You are supplying a fixed offset. If that is your intent, then ok. But do recognize that there is a difference between an offset and a time zone. (See "Time Zone != Offset" in the timezone tag wiki.) For example, if you wanted to convert to US Eastern Time, you should use .tz('America/New_York) instead of .utcOffset("-0500"). (US Eastern time is at -4 for the date given, not -5.) You would need the moment-timezone addon to make this work.

  • Lastly, recognize that Moment is in maintenance mode. The moment team generally recommends Luxon for new development.

Upvotes: 1

Ashot Aleqsanyan
Ashot Aleqsanyan

Reputation: 4453

The moment js .utcOffset() method takes the offset in minutes.

so if you want to get 12:34 you need to use -300 instead of -0500

moment("2020-03-21T17:34:00Z").utcOffset(-300).format("hh:mm")

Upvotes: 1

Related Questions