Why getUnixTime fuction from date-fns returns 1970?

Viewed 31
import { format, getUnixTime } from "date-fns";

import { useState } from "react";
import "./styles.css";

export default function App() {
  const [unixTime, setUnixTime] = useState(Date.now());

  return (
    <div className="App">
      <input
        value={format(unixTime, "yyyy-MM-dd'T'HH:mm")}
        onChange={(e) => setUnixTime(getUnixTime(new Date(e.target.value)))}
        type="datetime-local"
      />
      <p>{format(unixTime, "PPp")}</p>
    </div>
  );
}

In the above code, when you change the date by selecting a date in the input field the date does not become the date that you selected but rather became Jan 20 1970. here is the demo (try select the date in the input field so you can see what i meant).

How to get the date that was selected?

1 Answers

You need to multiply the timestamp by a factor of 1000.

setUnixTime(getUnixTime(new Date(e.target.value)) * 1000).

This is because JS timestamps are kept in milliseconds as opposed to Unix timestamps which use seconds.

Related