【问题标题】:When I format two different times they both come out as the same time, is there a way to fix this?当我格式化两个不同的时间时,它们都同时出现,有没有办法解决这个问题?
【发布时间】:2019-10-03 11:18:31
【问题描述】:

当格​​式化 2 个不同的时间时,它们会同时出现。我正在使用 h:mm:ss a

   correctTime(time) {
    var convertedTime = moment().format("h:mm:ss", time);
    return convertedTime;
  }

进去的2次:

  • 2019-10-03T11:00:00
  • 2019-10-03T11:20:00

出来的2次:

  • 1:13:55
  • 1:13:55

我想得到什么:

  • 11:00:00
  • 11:20:00

有什么我做错了吗?

【问题讨论】:

  • 你应该使用这样的时刻:moment("2019-10-03T11:00:00").format("hh:mm:ss"),

标签: javascript reactjs momentjs


【解决方案1】:

当你这样做时:

moment().format("h:mm:ss", time)

您正在格式化当前时间。

您要做的是格式化变量“时间”。

如果你的变量'time'已经是时刻,只需调用time.format("h:mm:ss"),如果是javascript日期,将其转换为时刻,然后调用格式方法。

【讨论】:

    【解决方案2】:

    当您使用moment() 构造函数时,它会创建一个代表当前时间的时刻实例。因此,请改用parsing 来根据您提供的时间创建一个实例。

    然后将该实例格式化为使用提供日期格式作为第一个也是唯一参数的格式方法。

    var formatted = moment('2019-10-03T11:20:09').format("h:mm:ss");
    console.log(formatted);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js"></script>

    【讨论】:

      【解决方案3】:

      moment() 返回当前日期时间。

      因此,当您在当前日期格式化时,它会返回本地时区的当前日期。

      moment(time).format("hh:mm:ss")这是正确的格式。

      【讨论】:

        猜你喜欢
        • 2022-06-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-08-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多