styler
styler

Reputation: 16481

Using moment js how do display only the time from a UTC timestamp?

I have a timestamp 2016-09-14T10:44:55.027Z and I would like to only display the 10:44:55 part but I'm not completely sure how. I have access to the moment library but not sure how to pass this into moment and format it, also how could I add AM or PM?

moment("2016-09-14T10:44:55.027Z").format('hh:mm:ss')

seems to output 11:44:55?

jsFiddle http://jsfiddle.net/eemfu0ym/

Upvotes: 0

Views: 10409

Answers (1)

Matt Johnson-Pint
Matt Johnson-Pint

Reputation: 241485

Since your input contains the Z suffix, that means the input value is in UTC. However, you're passing it into the default moment constructor, which is local time, thus a conversion occurs.

To keep it in UTC, the simplest way is to just obtain the moment object in UTC mode to begin with.

var m = moment.utc("2016-09-14T10:44:55.027Z")

Once you have that, you can format it however you like:

m.format('HH:mm:ss')   // 24-hour clock time
m.format('hh:mm:ss A') // 12-hour time with meridiem (AM/PM)

See the moment formatting docs for other options. Do note that tokens are case sensitive.

Upvotes: 6

Related Questions