78

How do i extract the time using moment.js?

"2015-01-16T12:00:00"

It should return "12:00:00 pm". The string return will be passed to the timepicker control below.

http://jdewit.github.com/bootstrap-timepicker 

Any idea?

ove
  • 3,092
  • 6
  • 34
  • 51

4 Answers4

121

If you read the docs (http://momentjs.com/docs/#/displaying/) you can find this format:

moment("2015-01-16T12:00:00").format("hh:mm:ss a")

See JS Fiddle http://jsfiddle.net/Bjolja/6mn32xhu/

Pochen
  • 2,871
  • 3
  • 22
  • 27
  • 1
    For instance moment("2015-01-16T16:00:00").format("HH:mm:ss a") returns as "16:00:00 pm" ??? it should be "4:00:00 pm" ! – ove Jan 16 '15 at 07:38
  • Yes, take a look here http://jsfiddle.net/Bjolja/6mn32xhu/ What do you mean it did not work? Error message? Wrong format on output? – Pochen Jan 16 '15 at 07:38
  • i expect "4:00:00 pm" not 16pm – ove Jan 16 '15 at 07:39
  • 8
    Change HH to hh, so moment("2015-01-16T16:00:00").format("hh:mm:ss a"). I've updated the fiddle aswell – Pochen Jan 16 '15 at 07:41
34

You can do something like this

var now = moment();
var time = now.hour() + ':' + now.minutes() + ':' + now.seconds();
time = time + ((now.hour()) >= 12 ? ' PM' : ' AM');
Ancient
  • 3,007
  • 14
  • 55
  • 104
8

Use format method with a specific pattern to extract the time. Working example

var myDate = "2017-08-30T14:24:03";
console.log(moment(myDate).format("HH:mm")); // 24 hour format
console.log(moment(myDate).format("hh:mm a")); // use 'A' for uppercase AM/PM
console.log(moment(myDate).format("hh:mm:ss A")); // with milliseconds
<script src="https://momentjs.com/downloads/moment.js"></script>
Deepu Reghunath
  • 8,132
  • 2
  • 38
  • 47
5

This is the good way using formats:

const now = moment()
now.format("hh:mm:ss K") // 1:00:00 PM
now.format("HH:mm:ss") // 13:00:00

Red more about moment sring format

uruapanmexicansong
  • 3,068
  • 1
  • 18
  • 22