this will be my first time to use javascript as a part of my project. And i need to convert a string in format HH:mm AM/PM to a 24 hr format (00:00:00) time. Please help guys! Thank you in advance.
Asked
Active
Viewed 2,775 times
0
-
First split it into the parts (`time.split(/[\s:]/)` might do), then inspect the am/pm part and add 12 to the hours, or not, depending on what you find. Then return a formatted string with the values. – RobG Dec 18 '13 at 10:03
1 Answers
1
Try with:
var input = '10:23 PM',
matches = input.toLowerCase().match(/(\d{1,2}):(\d{2}) ([ap]m)/),
output = (parseInt(matches[1]) + (matches[3] == 'pm' ? 12 : 0)) + ':' + matches[2] + ':00';
console.log(output); // 22:23:00

hsz
- 148,279
- 62
- 259
- 315
-
Thank you sir, but how about an input of "6:45 PM"? What's the best way to determine the input of user either "6:45 PM or 10:56 AM"? You code sir running successfully for 06:23 AM and not with 6:23 AM. Thanks Sir. – Aljie Dec 18 '13 at 12:17
-
1
-
-