【问题标题】:format difference in moment瞬间的格式差异
【发布时间】:2019-11-10 20:57:51
【问题描述】:

我有一些代码。现在 {time} 的结果是 1000 毫秒。我需要将这些毫秒转换为 00:00:01 之类的格式。 我知道我应该使用 moment().format('hh:mm:ss'),但问题是我不知道在哪里可以使用它来使其正常工作。 泰来帮忙!

import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";
import moment from "moment";

import "./styles.css";

const App = () => {
  const [time, setTime] = useState('');

  useEffect(() => {
    reqEmulation();
  });

  const reqEmulation = async () => {
    const timeStart = moment();
    const promise = new Promise(res => {
      setTimeout(() => {
        const timeEnd = moment();
        res(timeEnd.diff(timeStart));
      }, 1000);
    });
    let result = await promise;
    setTime(result);
  };

  return (
    <div className="App">
      <p>{time}</p>
    </div>
  );
};

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

我希望输出 00:00:01,但实际输出是 1000 毫秒。

【问题讨论】:

  • 你能分享timeStart的格式吗,比如一个例子?
  • 听起来像你想要的duration

标签: javascript momentjs


【解决方案1】:

您可以在将其存储到时间变量之前对其进行格式化:

...
let result = await promise;
setTime(moment(result).format('hh:mm:ss'));
...

如果你想以秒为单位的持续时间,你可以使用以下代码:

...
let result = await promise;
setTime(moment.duration(result).asSeconds());
...

【讨论】:

    猜你喜欢
    • 2018-12-25
    • 1970-01-01
    • 1970-01-01
    • 2014-01-03
    • 2012-10-11
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    相关资源
    最近更新 更多