最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Using moment js how do display only the time from a UTC timestamp? - Stack Overflow

programmeradmin1浏览0评论

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 pletely 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 /

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 pletely 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/eemfu0ym/

Share Improve this question asked Sep 16, 2016 at 14:29 stylerstyler 16.5k25 gold badges85 silver badges139 bronze badges 4
  • UTC timestamps are generally converted to the local timezone when parsed through the Date constructor in javascript, which is why it adds an hour. – adeneo Commented Sep 16, 2016 at 14:32
  • 1 moment("2016-09-14T10:44:55.027Z").utc().format('hh:mm:ss'). To get an output with AM/PM use .format("LTS") (only available in versions >= 2.8.4) – Andreas Commented Sep 16, 2016 at 14:33
  • Or without an entire library -> "2016-09-14T10:44:55.027Z".match(/T(.*?)\./)[1] – adeneo Commented Sep 16, 2016 at 14:36
  • moment(value).locale('en').format(/* ... */); – arjun kori Commented Sep 16, 2016 at 14:37
Add a ment  | 

1 Answer 1

Reset to default 6

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.

发布评论

评论列表(0)

  1. 暂无评论