How do you display JavaScript datetime in 12 hour AM/PM format?

后端 未结 27 3077
慢半拍i
慢半拍i 2020-11-22 02:36

How do you display a JavaScript datetime object in the 12 hour format (AM/PM)?

27条回答
  •  温柔的废话
    2020-11-22 03:14

    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.

提交回复
热议问题