简体   繁体   English

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

[英]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? 如何在JavaScript中将字符串时间转换为时间对象?

Required output = Thu Aug 14 2014 12:00:00 GMT+0530 (IST) 所需的输出= 2014年8月14日,星期四,格林尼治标准时间+0530(IST)

Because i need to compare startTime with current time... 因为我需要将startTime与当前时间进行比较...

See Date.prototype.setHours() 参见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/ JSFiddle〜http: //jsfiddle.net/tp1L63bu/

Cleaning up/consolidating/testing edge cases, of what Phil suggested above: 清理/合并/测试边际案例,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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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