将HH:mm转换为Moment.js

Ric*_*ard 17 javascript momentjs

所以我有一些时间数据如下:

10:45 PM
11:35 PM
12:06 AM
01:34 AM
Run Code Online (Sandbox Code Playgroud)

所有这些时间都在,America/Los_Angeles并且每次都保证09:00 PM在今天的时区之后.所以那些过了午夜的时间明天就会发生.

是否有一种优雅的方式将这些时间从当前格式转换为moment.js对象,并将时间固定到适当的日期.

Geo*_*oth 15

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;
}
Run Code Online (Sandbox Code Playgroud)


Kok*_*iwi 13

发现于moment.js doc:

moment('10:45 PM', 'HH:mm a')
Run Code Online (Sandbox Code Playgroud)

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

  • 不,这不起作用,因为'01:00 AM'的时间将映射到当前而不是第二天. (2认同)

小智 8

时刻('09:00','h:mm a').格式('h:mm a');