簡體   English   中英

兩個 Javascript 日期之間的時差

[英]Time Difference Between Two Javascript Dates

我無法計算出兩個日期之間的時差來計算倒數計時器。 我一直在關注許多不同的在線資源,但仍然無法正常工作。 daysDiff 未顯示在屏幕上。 這是我的代碼:

const currentDate = (new Date).toUTCString();
const futureDate = new Date(2028, 0, 1, 12, 0, 0);
const diff = futureDate.getTime() - currentDate.getTime();
const daysDiff = diff / (1000 & 60 * 60 * 24);

const render = () => {
    ReactDOM.render(
        React.createElement(
            "div",
            null,
            React.createElement('pre', null, daysDiff.toString()),
        ),
        document.getElementById('CarbonClock'),
    );
}

setInterval(render, 1000);

任何意見,將不勝感激。

您可以使用 Date javascript native object 執行此操作,也可以使用 moment。 如果您要進行大量日期操作,我建議您使用 moment。 這只是另一個選項,因為已經提供了日期選項

您可以從多種格式中獲得差異,但這里是一個快速示例,可在您的代碼中使用所提供的資源

 const future= moment([2028, 0, 1, 12, 0, 0]);
 const current = moment();
 const diffDays = future.diff(current, 'days');

這是一個示例,提供了所有類型的方法來初始化時刻 object 並創建差異。

   moment(Moment|String|Number|Date|Array)
     .diff(Moment|String|Number|Date|Array);   

資源:

https://momentjscom.readthedocs.io/en/latest/moment/04-displaying/07-difference/

問題

  • currentDate需要是 JS 日期 object 才能在其上調用getTime
  • diff計算錯字,應該是diff / (1000 * 60 * 60 * 24)

樣品溶液

import React, { useEffect, useState } from "react";

export default function App() {
  const computeDiff = () => {
    const currentDate = new Date();
    const futureDate = new Date(2028, 0, 1, 12, 0, 0);
    const diff = futureDate.getTime() - currentDate.getTime();
    return diff / (1000 * 60 * 60 * 24);
  };
  const [daysDiff, setDaysDiff] = useState(computeDiff());

  useEffect(() => {
    const timerId = setInterval(() => {
      setDaysDiff(computeDiff());
    }, 1000);

    return () => clearInterval(timerId);
  }, []);


  return <pre>{daysDiff.toString()}</pre>;
}
  • computeDiff是一個 function,具有計算和返回天數差異的分解邏輯。
  • useEffect hook 用於啟動更新間隔以使用天數差異更新本地組件 state(重新渲染)並返回清理 function 以在組件卸載時清除間隔。

編輯兩個 javascript 日期之間的時間差

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM