如何将OpenWeatherAPI返回数据中的UTC时间戳转换为字符串?
dt) to Date String Got it, turning those dt field timestamps from OpenWeatherAPI into human-readable date strings is totally doable—here are a few practical methods depending on whether you want to use native JS or a date library:
1. Native JavaScript (No External Libraries)
OpenWeatherAPI returns dt as a UTC timestamp in seconds, but JavaScript's Date object works with milliseconds. First, multiply the timestamp by 1000, then use built-in methods to format it:
// Example forecast item from your API response const forecastItem = { dt: 1519074000, main: {}, /* ...other fields */ }; // Convert seconds to milliseconds and create Date object const date = new Date(forecastItem.dt * 1000); // Option 1: Get a standard UTC string (e.g., "Thu, 22 Feb 2018 03:00:00 GMT") const utcDateString = date.toUTCString(); // Option 2: Get a localized string (varies by user's system settings) const localDateString = date.toLocaleString(); // Option 3: Custom UTC format (e.g., "2018-02-22 03:00:00 UTC") const customUtcFormat = `${date.getUTCFullYear()}-${String(date.getUTCMonth() + 1).padStart(2, '0')}-${String(date.getUTCDate()).padStart(2, '0')} ${String(date.getUTCHours()).padStart(2, '0')}:${String(date.getUTCMinutes()).padStart(2, '0')}:${String(date.getUTCSeconds()).padStart(2, '0')} UTC`;
Note: getUTCMonth() returns 0-indexed values (0 = January), so we add 1 to get the correct month number. padStart(2, '0') ensures single-digit days/months/hours get a leading zero.
2. Use Day.js (Lightweight, Modern Library)
Day.js is a tiny, fast alternative to Moment.js (which is no longer maintained). It handles second-based timestamps directly with unix():
// First install Day.js: npm install dayjs import dayjs from 'dayjs'; const forecastItem = { dt: 1519074000 }; // Format as UTC string (custom format example) const utcFormatted = dayjs.unix(forecastItem.dt).utc().format('YYYY-MM-DD HH:mm:ss [UTC]'); // Format as local time const localFormatted = dayjs.unix(forecastItem.dt).format('YYYY-MM-DD HH:mm:ss');
It lets you define any format string you want—super flexible for matching your app's UI needs.
3. Moment.js (Legacy Projects Only)
If you're working on an older project that already uses Moment.js, here's how to do it:
// Install Moment.js if needed: npm install moment import moment from 'moment'; const forecastItem = { dt: 1519074000 }; const utcFormatted = moment.unix(forecastItem.dt).utc().format('YYYY-MM-DD HH:mm:ss UTC');
Note: Moment.js is no longer actively maintained, so Day.js is the better choice for new projects.
Key Reminder
Always double-check that you're converting the second-based timestamp to milliseconds if using native JS—forgetting to multiply by 1000 will give you a date way back in the 1970s!
内容的提问来源于stack exchange,提问作者edwin walela

