简体   繁体   English

如何从特定日期制作倒数计时器

[英]How to make a countdown timer from a specific date

In ReactJS, I need to make a countdown timer from "09/19/2020" and have it all displayed on my page What this timer considered month, days, hours, etc. For this timer to count the month, days, hours, etc. from a certain point in time.在 ReactJS 中,我需要制作一个从“09/19/2020”开始的倒数计时器,并将其全部显示在我的页面上 这个计时器考虑的是月、日、小时等。对于这个计时器来计算月、天、小时,等从某个时间点。 Not BEFORE any date, but FROM a certain date.不是在任何日期之前,而是从某个日期开始。 Available from "09/19/2020"可从“09/19/2020”开始

My code:我的代码:

import React from "react";

const Timer = () => {
}

export default Timer

You can convert the past datetime to unix time and subtract that from the current datetime in unix time, and then convert the difference back to whatever display of time you want.您可以将过去的日期时间转换为 unix 时间并从 unix 时间的当前日期时间中减去它,然后将差异转换回您想要的任何时间显示。 Do this every second to obtain a timer.每秒执行一次以获取计时器。

You could also use a library like moment.js , which has a .unix() function to convert easily.您还可以使用像moment.js这样的库,它有一个.unix()函数可以轻松转换。

Try using this example:尝试使用此示例:

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

function calcDiffInMinutes(dateA, dateB) {
  return Math.floor(((dateA.getTime() - dateB.getTime()) / 1000) % 60); // TODO CALCULATIONS HERE
}

export default ({ dateFrom }) => {
  const [currentDate, setCurrentDate] = useState(new Date());
  const [minutesDiff, setMinutesDiff] = useState(
    calcDiffInMinutes(currentDate, dateFrom)
  );

  useEffect(() => {
    const timeoutId = setTimeout(() => {
      setCurrentDate(new Date());
    }, 1000);

    return () => clearTimeout(timeoutId);
  }, [currentDate]);

  useEffect(() => {
    setMinutesDiff(calcDiffInMinutes(currentDate, dateFrom));
  }, [currentDate, dateFrom]);

  return (
    <div>
      <div>Date From: {dateFrom.toISOString()}</div>
      <div>CountDown value: {minutesDiff}</div>
    </div>
  );
};

Put this in a separate component file called eg CountdownTimer .把它放在一个单独的组件文件中,例如CountdownTimer And then you can use it in your app.然后你可以在你的应用程序中使用它。

See the full example here: https://codesandbox.io/s/react-playground-forked-vmqvy?file=/CountdownTimer.js在此处查看完整示例: https : //codesandbox.io/s/react-playground-forked-vmqvy?file=/CountdownTimer.js

PS calcDiffInMinutes should be done by you to calculate real diff in minutes. PS calcDiffInMinutes应该由您完成以在几分钟内计算出真正的差异。 You'll also need to create such functions for days/months etc. Or change to single function that returns an object with all the differences.您还需要为天/月等创建此类函数。或者更改为返回具有所有差异的对象的单个函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM