Richard
Richard

Reputation: 61259

Convert HH:mm into Moment.js

So I have some time data such as follows:

10:45 PM
11:35 PM
12:06 AM
01:34 AM

All of these times are in America/Los_Angeles and each time is guaranteed to be after 09:00 PM in today in that timezone. So that times which are past midnight take place tomorrow.

Is there an elegant way to convert these times from the current format into moment.js objects with the times pinned to the appropriate day.

Upvotes: 35

Views: 86802

Answers (4)

José Farías
José Farías

Reputation: 411

moment('09:00','h:mm a').format('h:mm a');

Upvotes: 41

Aryeh Armon
Aryeh Armon

Reputation: 2175

You can use the tz() method:

var date = moment().tz("America/Los_Angeles").startOf('day');
date.hour(22);
date.minutes(45);

Then convert it to local time:

date.local().toDate();

Upvotes: 1

Geoffrey Booth
Geoffrey Booth

Reputation: 7366

function getMomentFromTimeString(str) {
  var t = moment(str, 'HH:mm A');
  // Now t is a moment.js object of today's date at the time given in str

  if (t.get('hour') < 22) // If it's before 9 pm
    t.add('d', 1); // Add 1 day, so that t is tomorrow's date at the same time

  return t;
}

Upvotes: 15

KokaKiwi
KokaKiwi

Reputation: 605

Found in moment.js doc:

moment('10:45 PM', 'HH:mm a')

http://momentjs.com/docs/#/parsing/string-format/

Upvotes: 21

Related Questions