我目前试图显示用户的时间而不显示秒。是否有一种方法,我可以这样做使用Javascript的.toLocaleTimeString()?

做这样的事情:

var date = new Date();
var string = date.toLocaleTimeString();

将显示用户的时间与每个单位,例如,目前显示为3:39:15 PM。我是否能够显示相同的字符串,只是没有秒?(例如下午3时39分)


当前回答

下面是一个函数,用注释解释:

  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
  }

正如其他人所指出的那样,toLocaleTimeString()可以在不同的浏览器中以不同的方式实现,因此这种方式提供了更好的控制。

要了解更多关于Javascript Date对象的信息,可以参考https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

其他回答

我想让它有日期和时间,但没有秒,所以我用了这个:

var dateWithoutSecond = new Date();
dateWithoutSecond.toLocaleTimeString([], {year: 'numeric', month: 'numeric', day: 'numeric', hour: '2-digit', minute: '2-digit'});

它产生了以下输出:

2020年7月29日,下午2:46

这正是我所需要的。使用过FireFox。

你可以设置选项,在这个页面上你可以设置,去掉秒,像这样

var dateWithouthSecond = new Date();
dateWithouthSecond.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});

支持Firefox、Chrome、IE9+和Opera。在你的web浏览器控制台试试。

你可以试试这个,它能满足我的需求。

var d = new Date();
d.toLocaleTimeString().replace(/:\d{2}\s/,' ');

or

d.toLocaleString().replace(/:\d{2}\s/,' ');

下面是一个函数,用注释解释:

  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
  }

正如其他人所指出的那样,toLocaleTimeString()可以在不同的浏览器中以不同的方式实现,因此这种方式提供了更好的控制。

要了解更多关于Javascript Date对象的信息,可以参考https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

我只能从用户的localeTimeString中得到小时

const americanTime = date.toLocaleTimeString("en-US", { timeZone: 'America/New_York', hour: 'numeric', hour12: false })
    
const timeInHours = americanTime; 

在本例中,我使用New_York作为用户的位置。