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

后端 未结 27 3076
慢半拍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:02

    In modern browsers, use Intl.DateTimeFormat and force 12hr format with options:

        let now = new Date();
    
        new Intl.DateTimeFormat('default',
            {
                hour12: true,
                hour: 'numeric',
                minute: 'numeric'
            }).format(now);
    
        // 6:30 AM
    

    Using default will honor browser's default locale if you add more options, yet will still output 12hr format.

提交回复
热议问题