【问题标题】:How to change the format of time?如何更改时间格式?
【发布时间】:2021-11-20 01:25:37
【问题描述】:

我有一个时间类型的输入,当我点击它时,我可以从 1-12、分钟和上午/下午选择一个小时。 snapshot

当我呈现选择时,它会以 24 小时格式显示。但是,我希望它采用 12 小时格式。
我正在开发一个 react-redux 应用程序。

<input type='time' 
          onChange={(e) => this.setState({
            time: e.target.value
          })}
          value={this.state.time} />
state = {
    time: ''
  }
  render = () => {
    return (
      <span>{time}</span>
    )
  }

【问题讨论】:

    标签: javascript reactjs redux jsx


    【解决方案1】:

    您可以使用此功能更改时间格式:

    const timeConvertor = (time) => {
      // first checks the correct time format and then split it into components
      time = time.toString ().match (/^([01]\d|2[0-3])(:)([0-5]\d)(:[0-5]\d)?$/) || [time];
    
      if (time.length > 1) { // If the time format is correct
        time = time.slice (1);  // Remove full string match value
        time[5] = +time[0] < 12 ? 'AM' : 'PM'; // Set AM/PM based on given hour
        time[0] = +time[0] % 12 || 12; // change the hour based on AM/PM
      }
      return time.join (''); // return new time format as a String
    }
    

    例如:

    timeConvertor('20:50:00'); // will return '8:50:00PM'
    

    【讨论】:

    • 我不明白。
    • @QatrEl-Nada 它是一个函数,您可以将 24 小时格式的时间作为字符串输入传递,并以 12 小时格式接收时间作为输出。
    猜你喜欢
    • 2012-01-03
    • 2018-03-27
    • 1970-01-01
    • 1970-01-01
    • 2015-09-12
    • 2011-07-27
    • 2015-03-24
    相关资源
    最近更新 更多