DMur
DMur

Reputation: 659

Time Difference Between Two Javascript Dates

I cant get my time difference between two dates to work out for a countdown timer. I have been following a number of different online sources but it's still not working. daysDiff is not displaying on screen. This is my code:

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);

Any advice would be appreciated.

Upvotes: 0

Views: 215

Answers (2)

Edward Romero
Edward Romero

Reputation: 3106

You can do this with Date javascript native object or you can use moment. I would suggest using moment if you are doing a lot of date manipulation. This is just another option since Date option was already provided

You can get the difference in many formats but here is a quick example to use in your code from the resource provided

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

Here is an example providing all types of ways to initialize the moment object and create the diff.

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

Resource:

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

Upvotes: 1

Drew Reese
Drew Reese

Reputation: 203198

Issues

  • currentDate needs to be a JS Date object in order to invoke getTime on it.
  • Typo in diff calculation, it should be diff / (1000 * 60 * 60 * 24)

Sample Solution

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 is a function with factored logic to compute and return the days diff.
  • useEffect hook is to start the update interval to update local component state with the days diff (to rerender) and returns a clean up function to clear the interval when the component unmounts.

Edit time-difference-between-two-javascript-dates

Upvotes: 0

Related Questions