JavaScript日期转换返回旧日期,疑与第三方API返回值相关
Hey there! Let's break down exactly what's going on here and how to fix it:
Why Your Date Is Showing Up as 1970
First off, this isn't an API issue—it's a mismatch in timestamp units between the API and JavaScript's Date function:
- JavaScript's
Dateconstructor expects a millisecond-level timestamp (count of milliseconds since January 1, 1970 UTC) - The value
1521441000your API returns is a second-level timestamp (count of seconds since that same epoch). When you pass this directly toDate, it only accounts for ~17 days of time since 1970, hence the incorrect early 1970s date.
Quick Fix to Get the Correct 2018 Date
Just multiply the API's timestamp by 1000 to convert it to milliseconds, and JavaScript will parse it correctly:
const apiTimestamp = 1521441000; const correctDate = new Date(apiTimestamp * 1000); console.log(correctDate.toString()); // Will output something like "Wed Mar 21 2018 ..." which matches your 2018 filter
How to Confirm It's Not the API
To double-check the API is working as intended:
- Plug the timestamp
1521441000into a timestamp converter (make sure to select "seconds" as the unit) — it should map to a date in March/April 2018 - Check the API's documentation to confirm it explicitly returns second-level timestamps (this is a common standard for backend APIs, since it's more compact than milliseconds)
内容的提问来源于stack exchange,提问作者Jyothish Bhaskaran
相关产品推荐
相关产品推荐

