iamkun / dayjs

⏰ Day.js 2kB immutable date-time library alternative to Moment.js with the same modern API
https://day.js.org
MIT License
47.1k stars 2.31k forks source link

The values ​​of dayjs().unix() and dayjs().utc().unix are the same, but dayjs().format('YYYY-MM-DD HH:mm:ss') and dayjs().utc().format('YYYY-MM-DD HH:mm:ss') are different #2710

Open XiaoXiaoWu98 opened 3 months ago

XiaoXiaoWu98 commented 3 months ago

Describe the bug The values ​​of dayjs().unix() and dayjs().utc().unix are the same, but dayjs().format('YYYY-MM-DD HH:mm:ss') and dayjs().utc().format('YYYY-MM-DD HH:mm:ss') are different

Expected behavior

The values ​​of dayjs().unix() and dayjs().utc().unix should be different

Information

potter-man commented 3 months ago

Unix time should not be different. After the format you see different "numbers" but omit timezone. In fact it's actually the same date local zone and UTC.

XiaoXiaoWu98 commented 3 months ago

Unix time should not be different. After the format you see different "numbers" but omit timezone. In fact it's actually the same date local zone and UTC.

But if I want to get the UTC timestamp, I can only do it through dayjs().utc().format('YYYY-MM-DD HH:mm:ss').unix(), not directly dayjs().utc().unix(). I think the timestamp should be consistent with the time format after format.

potter-man commented 3 months ago

If you need unix timestamp (seconds) you don't need to format, just call .unix() on dayjs instance

dayjs().unix()                                             // 1725008613
dayjs.utc().unix()                                         // 1725008613
dayjs('2024-08-30T00:00:00Z').unix()                       // 1724976000
dayjs.utc('2024-08-30T00:00:00Z').unix()                   // 1724976000

As I mentioned you just lose information about zone and dayjs parses string in local zone

dayjs(dayjs().format('YYYY-MM-DD HH:mm:ss')).unix()        // 1725008613
dayjs(dayjs().utc().format('YYYY-MM-DD HH:mm:ss')).unix()  // 1724997813 - Z is lost

Default format includes zone

dayjs(dayjs().format()).unix()                             // 1725008613
dayjs(dayjs().utc().format()).unix()                       // 1725008613

Or you can add Z to your custom format

dayjs(dayjs().format('YYYY-MM-DD HH:mm:ssZ')).unix()       // 1725008613
dayjs(dayjs().utc().format('YYYY-MM-DD HH:mm:ssZ')).unix() // 1725008613