如何在JavaScript中将“12:00 PM”转换为Date对象?

时间:2014-08-14 04:39:57

标签: javascript date

var time = "12:00 PM"
var startTime = Date.parse(time); // output is NaN
alert(startTime);

如何在JavaScript中将字符串时间转换为时间对象?

所需产出= 2014年8月14日星期四12:00:00 GMT + 0530(IST)

因为我需要将startTime与当前时间进行比较......

2 个答案:

答案 0 :(得分:2)

请参阅Date.prototype.setHours()

var d = new Date();
d.setHours(12, 0, 0, 0);
alert(d);

如果你必须解析时间字符串,你可以试试这个......

var time = '12:00 PM';
var startTime = new Date();
var parts = time.match(/(\d+):(\d+) (AM|PM)/);
if (parts) {
    var hours = parseInt(parts[1]),
        minutes = parseInt(parts[2]),
        tt = parts[3];
    if (tt === 'PM' && hours < 12) hours += 12;
    startTime.setHours(hours, minutes, 0, 0);
}
alert(startTime);

JSFiddle~ http://jsfiddle.net/tp1L63bu/

答案 1 :(得分:0)

清理/合并/测试边缘情况,如Phil上面所建议:

const militaryTime = (time, date = new Date()) => {
  const parts = time.trim().match(/(\d+):(\d+)\s?((am|AM)|(pm|PM))/)
  const p = {
    hours: parseInt(parts[1]),
    minutes: parseInt(parts[2]),
    period: parts[3].toLowerCase()
  }

  if (p.hours === 12) {
    if (p.period === 'am') {
      date.setHours(p.hours - 12, p.minutes)
    }
    if (p.period === 'pm') {
      date.setHours(p.hours, p.minutes)
    }
  } else {
    if (p.period === 'am') {
      date.setHours(p.hours, p.minutes)
    }
    if (p.period === 'pm') {
      date.setHours(p.hours + 12, p.minutes)
    }
  }

  return date
}

militaryTime('  4:00 am    ') // Thu May 30 2019 04:00:48 GMT-0400 (Eastern Daylight Time)
militaryTime('4:00pm') // Thu May 30 2019 16:00:42 GMT-0400 (Eastern Daylight Time)

militaryTime('12:00am') // Thu May 30 2019 00:00:25 GMT-0400 (Eastern Daylight Time)
militaryTime('12:00pm') // Thu May 30 2019 12:00:46 GMT-0400 (Eastern Daylight Time)