Reputation: 223
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...
Upvotes: 0
Views: 4077
Reputation: 7695
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)
Upvotes: 0
Reputation: 165058
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/
Upvotes: 3