How do you display a JavaScript datetime object in the 12 hour format (AM/PM)?
Here's a way using regex:
console.log(new Date('7/10/2013 20:12:34').toLocaleTimeString().replace(/([\d]+:[\d]{2})(:[\d]{2})(.*)/, "$1$3"))
console.log(new Date('7/10/2013 01:12:34').toLocaleTimeString().replace(/([\d]+:[\d]{2})(:[\d]{2})(.*)/, "$1$3"))
This creates 3 matching groups:
([\d]+:[\d]{2})
- Hour:Minute(:[\d]{2})
- Seconds(.*)
- the space and period (Period is the official name for AM/PM)Then it displays the 1st and 3rd groups.
WARNING: toLocaleTimeString() may behave differently based on region / location.