You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何date-fns的getUnixTime返回1970?如何获取选中的日期?

问题解决:日期选择后显示1970年的修复方案

问题原因

问题出在时间戳的单位混淆:

  • getUnixTime返回的是秒级Unix时间戳(从1970年起始的秒数)
  • 而date-fns的format函数、JavaScript的Date对象默认使用毫秒级时间戳(从1970年起始的毫秒数)

当你把秒级时间戳传给format时,它会被当作毫秒数解析,相当于只过了几十/几百秒,因此显示的日期会是1970年初的日期。


解决方案

方案一:转换时间戳单位

将getUnixTime返回的秒数乘以1000,转成毫秒级时间戳:

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)) * 1000)}
        type="datetime-local"
      />
      <p>{format(unixTime, "PPp")}</p>
    </div>
  );
}

方案二:直接存储Date对象(推荐)

避免时间戳单位混淆,直接操作Date对象,代码更直观易懂:

import { format } from "date-fns";
import { useState } from "react";
import "./styles.css";

export default function App() {
  const [selectedDate, setSelectedDate] = useState(new Date());

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

内容的提问来源于stack exchange,提问作者Esa Kurniawan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 19:40:19