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

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

    It will return the following format like

    09:56 AM
    

    appending zero in start for the hours as well if it is less than 10

    Here it is using ES6 syntax

    const getTimeAMPMFormat = (date) => {
      let hours = date.getHours();
      let minutes = date.getMinutes();
      const ampm = hours >= 12 ? 'PM' : 'AM';
      hours = hours % 12;
      hours = hours ? hours : 12; // the hour '0' should be '12'
      hours = hours < 10 ? '0' + hours : hours;
      // appending zero in the start if hours less than 10
      minutes = minutes < 10 ? '0' + minutes : minutes;
      return hours + ':' + minutes + ' ' + ampm;
    };
    console.log(getTimeAMPMFormat(new Date)); // 09:59 AM

    0 讨论(0)
  • 2020-11-22 03:19

    Short RegExp for en-US:

    var d = new Date();
    d = d.toLocaleTimeString().replace(/:\d+ /, ' '); // current time, e.g. "1:54 PM"
    
    0 讨论(0)
  • 2020-11-22 03:21

    If you just want to show the hours then..

    var time = new Date();
    console.log(
      time.toLocaleString('en-US', { hour: 'numeric', hour12: true })
    );  

    Output : 7 AM

    If you wish to show the minutes as well then...

    var time = new Date();
    console.log(
      time.toLocaleString('en-US', { hour: 'numeric', minute: 'numeric', hour12: true })
    );

    Output : 7:23 AM

    0 讨论(0)
  • 2020-11-22 03:22

    function formatAMPM(date) {
      var hours = date.getHours();
      var minutes = date.getMinutes();
      var ampm = hours >= 12 ? 'pm' : 'am';
      hours = hours % 12;
      hours = hours ? hours : 12; // the hour '0' should be '12'
      minutes = minutes < 10 ? '0'+minutes : minutes;
      var strTime = hours + ':' + minutes + ' ' + ampm;
      return strTime;
    }
    
    console.log(formatAMPM(new Date));

    0 讨论(0)
  • 2020-11-22 03:22

    use dateObj.toLocaleString([locales[, options]])

    Option 1 - Using locales

    var date = new Date();
    console.log(date.toLocaleString('en-US'));
    

    Option 2 - Using options

    var options = { hour12: true };
    console.log(date.toLocaleString('en-GB', options));
    

    Note: supported on all browsers but safari atm

    0 讨论(0)
  • 2020-11-22 03:23

    Use Moment.js for this

    Use below codes in JavaScript when using moment.js

    H, HH       24 hour time
    h, or hh    12 hour time (use in conjunction with a or A)
    

    The format() method returns the date in specific format.

    moment(new Date()).format("YYYY-MM-DD HH:mm"); // 24H clock
    moment(new Date()).format("YYYY-MM-DD hh:mm A"); // 12H clock (AM/PM)
    moment(new Date()).format("YYYY-MM-DD hh:mm a"); // 12H clock (am/pm)
    
    0 讨论(0)
提交回复
热议问题