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

后端 未结 8 1365
温柔的废话
温柔的废话 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 ;)

提交回复
热议问题