API返回科学计数法时间戳解析及JavaScript转换方法咨询
Hey there! Let's tackle your date format questions step by step.
The values like 1.5146712e+12 are millisecond-level Unix timestamps presented in scientific notation.
Unix timestamps count the number of milliseconds (in this case) that have passed since the Unix Epoch: January 1, 1970, 00:00:00 UTC. The scientific notation is just a compact way to represent large integer values—if you convert 1.5146712e+12 to a regular integer, you get 1514671200000, which maps to December 30, 2017 UTC.
There are a couple of straightforward ways to do this using native JavaScript features:
Option 1: Manual formatting with Date object properties
You can create a Date instance from the timestamp, then extract and format the day, month, and year manually. Note that JavaScript's getMonth() returns a 0-indexed value (0 = January, 11 = December), so you'll need to add 1 to get the correct calendar month.
// Convert the scientific notation timestamp to a Date object const timestamp = 1.5146712e+12; const date = new Date(timestamp); // Extract individual components const day = String(date.getDate()).padStart(2, '0'); // Pad with leading zero for single-digit days const month = String(date.getMonth() + 1).padStart(2, '0'); // Adjust month index and pad const year = date.getFullYear(); // Format as DD/MM/YYYY (adjust order for MM/DD/YYYY if needed) const formattedDate = `${day}/${month}/${year}`; console.log(formattedDate); // Output: "30/12/2017"
Option 2: Use Intl.DateTimeFormat (recommended for localization)
For a cleaner, more flexible approach—especially if you need support for different locales—use the built-in Intl.DateTimeFormat API. It handles formatting automatically based on your desired locale and options.
const timestamp = 1.5146712e+12; const date = new Date(timestamp); // Configure the formatter for day, month, year (2-digit day/month, numeric year) const dateFormatter = new Intl.DateTimeFormat('zh-CN', { day: '2-digit', month: '2-digit', year: 'numeric' }); // Generate the formatted date string const formattedDate = dateFormatter.format(date); console.log(formattedDate); // Output: "2017/12/30" (for zh-CN locale; en-US would give "12/30/2017")
Quick note:
Double-check if your timestamp is in milliseconds or seconds. In this case, 1.5146712e+12 is milliseconds—if you had a second-level timestamp, you'd need to multiply by 1000 before passing it to the Date constructor.
内容的提问来源于stack exchange,提问作者Lee Maan

