【问题标题】:Formatting time error - "10.03" becomes "10.3"格式化时间错误 - “10.03”变成“10.3”
【发布时间】:2020-01-21 10:18:53
【问题描述】:

我有一个可以格式化的日期和时间。它大部分时间都有效,但如果时间在倒数第二个空格中有“0”,它将返回错误。例如,时间“10.30”将被正确格式化,但“10.03”将返回不带零的“10.3”。

我的代码:

const today: Date = new Date();
const date: Date = new Date(item.receivedDateTime);
let time: string;

if (date.getFullYear() === today.getFullYear() &&
  date.getMonth() === today.getMonth() &&
  date.getDate() === today.getDate()) {
  time = date.getHours() + ":" + date.getMinutes();
} else {
  time = date.getDate() + "/" + (date.getMonth() + 1);
}

以上将错误地格式化时间。代码有什么问题?我不喜欢使用 padstart,因为 IE11 或 moment.js 不支持它。

【问题讨论】:

  • 我认为你必须使用 ldap 函数在小值到 9 之前添加 '0'
  • 我给你做了一个sn-p。请添加ìtem`的示例
  • “代码有什么问题?” - 好吧,技术上没什么。你只是没有让它做你真正想要的。 getMinutes 返回一个整数,所以你不能指望一个前导零会神奇地突然出现。所以如果你想要一个,你必须确保它被添加到输出中。

标签: javascript reactjs typescript


【解决方案1】:

您可以将date.getMinutes() 的值保存在一个变量中并检查它是否小于10,如果是,则附加一个0

const minutes = date.getMinutes();
const formattedMinutes = (minutes < 10) ? '0' + minutes : minutes;

最后,使用格式化的值进行输出:

time = date.getHours() + ":" + formattedMinutes;

【讨论】:

    【解决方案2】:

    你可以使用一个简单的pad函数

    const pad = num => ("0"+num).slice(-2);
    
    const item = {"receivedDateTime":1570000000000}
    
    
    const today =  new Date();
    const date =   new Date(item.receivedDateTime);
    let time = "";
    
    if (date.getFullYear() === today.getFullYear() &&
        date.getMonth()    === today.getMonth() &&
        date.getDate()     === today.getDate()) {
     time = pad(date.getHours()) + ":" + pad(date.getMinutes());
    } else {
      time = pad(date.getDate()) + "/" + pad(date.getMonth() + 1);
    }
    console.log(time)

    【讨论】:

      【解决方案3】:

      而不是,

      time = date.getHours() + ":" + date.getMinutes();
      

      你可以使用,

      var minutes = d.getMinutes() > 9 ? d.getMinutes() : '0' + d.getMinutes();
      time = date.getHours() + ":" + minutes
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-12-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-24
        • 2017-11-16
        相关资源
        最近更新 更多