Changing the 1-24 hour to 1-12 hour for the “getHours()” Method

后端 未结 8 1363
温柔的废话
温柔的废话 2020-12-09 08:57

When I use the \"getHour()\" method in javascript, it displays the military time format. I need it to display the hour in numbers between 1-12 instead. Can anybody tell me

相关标签:
8条回答
  • 2020-12-09 09:44

    Other answers are indeed very good. But I think, following can be included too.

    var d = new Date();
    var hour = d.getHours(); 
    var minute = d.getMinutes();
    var fulltime = "";
    
    // create a 24 elements(0-23) array containing following values
    const arrayHrs = [12,1,2,3,4,5,6,7,8,9,10,11,12,1,2,3,4,5,6,7,8,9,10,11];
    
        // since getMinutes() returns 0 to 9 for upto 9 minutes, not 00 to 09, we can do this
        if(minute < 10) {
            minute = "0" + minute;
        }
    
        if( hour < 12) {
            // Just for an example, if hour = 11 and minute = 29
            fulltime = arrayHrs[hour] + ":" + minute + " AM"; // fulltime = 11:29 AM
        }
        else {
            // similarly, if hour = 22 and minute = 8
            fulltime = arrayHrs[hour] + ":" + minute + " PM"; // fulltime = 10:08 PM
        }
    

    See what I did there in arrayHrs ;)

    0 讨论(0)
  • 2020-12-09 09:48
    getDateTime = () => {
        const today = new Date();
        const day = today.toLocaleDateString('en-us', { weekday: 'short' });
        const month = today.toLocaleString('en-us', { month: 'short' });
        const date = today.getDate()
        const year = today.getFullYear()
        const hours = today.getHours()
        const minutes = today.getMinutes().toString()
        var dayORnight = "AM";
        if (hours > 11) { dayORnight = "PM"; }
        if (hours > 12) { hours = hours - 12; }
        if (hours == 0) { hours = 12; }
        if (hours < 10) { hours = "0" + hours; }
        if (minutes < 10) { minutes = "0" + minutes; }
    
        const datetime = `${day}, ${month} ${date}, ${year} at ${hours}:${minutes} ${dayORnight}`;
        console.log(datetime)
    }
    
    0 讨论(0)
  • 2020-12-09 09:53

    An answer similar to the accepted, but without the || operator.

    Purely arithmetical:

    // returns the hours number for a date, between 1 and 12
    function hours12(date) { return (date.getHours() + 11) % 12 + 1; }
    

    Test it here. Simulating hours 0 - 23:

    var demoTable = document.getElementById("demo");
    
    // simulate getHours() values 0-23
    for (i = 0; i < 24; i++) {
      var row = demoTable.insertRow(-1);
      var format24Cell = row.insertCell(0);
      var conversionCell = row.insertCell(1);
      var format12Cell = row.insertCell(2);
      format24Cell.innerHTML = i;
      conversionCell.innerHTML = "( <b>" + i + "</b> + 11) % 12 + 1 =";
      
      // conversion takes place here
      format12Cell.innerHTML = (i + 11) % 12 + 1;
    }
    table {
      border-collapse: collapse;
      width: 100%;
    }
    
    table,
    th,
    td {
      border: 1px solid black;
    }
    
    th {
      padding: 0, 5px
    }
    
    td {
      padding-left: 5px;
    }
    <table id="demo">
      <tr>
        <th colspan="3">24 to 12 Hour Format Conversion Demo</th>
      <tr>
      <tr>
        <th>24 Hour Format</th>
        <th>Conversion</th>
        <th>12 Hour Format</th>
      </tr>
    </table>

    0 讨论(0)
  • 2020-12-09 09:54

    Why not do it the brief way? Math, people! :)

    // returns the hours number for a date, between 1 and 12
    function hours12(date) { return (date.getHours() + 24) % 12 || 12; }
    
    0 讨论(0)
  • 2020-12-09 09:57

    Shortest:

    const hours12 = date => (date.getHours() % 12  || 12);
    

    If you need padding with 0:

    const hours12 = date => ("0"+(date.getHours() % 12  || 12)).slice(-2);
    

    Another option, also with AM & PM:

    const hours12 = date => date.toLocaleString('en-US', { hour: 'numeric', hour12: true })
    
    0 讨论(0)
  • 2020-12-09 09:58

    This will correct 13 - 24 back to the range 1 - 12, and 0 back to 12:

    var hours = time.getHours();
    if (hours > 12) {
        hours -= 12;
    } else if (hours === 0) {
       hours = 12;
    }
    

    Also, you need to stop repeating yourself in your code. Call time.getHours() and time.getMinutes() and store their values just once each, and then worry about adding the leading zeroes, e.g.:

    function updateclock() {
    
        function pad(n) {
             return (n < 10) ? '0' + n : n;
        }
    
        var time = new Date();
        var hours = time.getHours();
        var minutes = time.getMinutes();
    
        if (hours > 12) {
            hours -= 12;
        } else if (hours === 0) {
            hours = 12;
        }
    
        var todisplay = pad(hours) + ':' + pad(minutes);
        document.getElementById("clock").innerHTML = todisplay;
    }
    
    0 讨论(0)
提交回复
热议问题