How do I use .toLocaleTimeString() without displaying seconds?

前端 未结 11 965
小蘑菇
小蘑菇 2020-12-07 15:56

I\'m currently attempting to display the user\'s time without displaying the seconds. Is there a way I can do this using Javascript\'s .toLocaleTimeString()?

Doing s

11条回答
  •  时光取名叫无心
    2020-12-07 16:57

    Here's a function that will do it, with comments that explain:

      function displayNiceTime(date){
        // getHours returns the hours in local time zone from 0 to 23
        var hours = date.getHours()
        // getMinutes returns the minutes in local time zone from 0 to 59
        var minutes =  date.getMinutes()
        var meridiem = " AM"
    
        // convert to 12-hour time format
        if (hours > 12) {
          hours = hours - 12
          meridiem = ' PM'
        }
        else if (hours === 0){
          hours = 12
        }
    
        // minutes should always be two digits long
        if (minutes < 10) {
          minutes = "0" + minutes.toString()
        }
        return hours + ':' + minutes + meridiem
      }
    

    Since, as others have noted, toLocaleTimeString() can be implemented differently in different browsers, this way gives better control.

    To learn more about the Javascript Date object, this is a good resource: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

提交回复
热议问题