简体   繁体   中英

How to covert “12:00 PM” into Date object in JavaScript?

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

How to convert a string time into time object in JavaScript?

Required output = Thu Aug 14 2014 12:00:00 GMT+0530 (IST)

Because i need to compare startTime with current time...

See Date.prototype.setHours()

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

If you must parse the time string, you can try this...

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/

Cleaning up/consolidating/testing edge cases, of what Phil suggested above:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM