我目前正在從 momentjs 遷移到 dayjs。
我堅持的部分是在嚴格模式下使用 ISO8601 轉換 Dayjs 物件,就像 momentjs 一樣。起初,我嘗試將物件轉換為CustomParseFormat如下所示的檔案描述。由于. _ _CustomParseFormat
const dayjs = require('dayjs');
const customParseFormat = require('dayjs/plugin/customParseFormat')
dayjs.extend(customParseFormat);
// not sure that dayjs is utilizing the format in below for ISO8601
const iso8601Format = 'YYYY-MM-DDTHH:mm:ss.sssZ'
const currentDate = new Date();
console.log(dayjs(currentDate, iso8601Format, true));
// the result is like below
// {
// '$L': 'en',
// '$u': undefined,
// '$d': Invalid Date,
// '$y': NaN,
// '$M': NaN,
// '$D': NaN,
// '$W': NaN,
// '$H': NaN,
// '$m': NaN,
// '$s': NaN,
// '$ms': NaN
// }
但是,如果我在沒有擴展的情況下轉換了物件CustomParseFormat,它似乎回傳了一個有效的物件。
const dayjs = require('dayjs');
// not sure that dayjs is utilizing the format in below for ISO8601
const iso8601Format = 'YYYY-MM-DDTHH:mm:ss.sssZ'
const currentDate = new Date();
console.log(dayjs(currentDate, iso8601Format, true));
// the result is like below
// M {
// '$L': 'en',
// '$d': 2022-06-10T02:59:43.585Z,
// '$x': {},
// '$y': 2022,
// '$M': 5,
// '$D': 10,
// '$W': 5,
// '$H': 11,
// '$m': 59,
// '$s': 43,
// '$ms': 585
// }
所以,我的問題是 dayjs 是否允許在不使用的情況下使用自定義格式決議日期CustomParseFormat?另外,它是否保證結果與momentjs相同?謝謝。
uj5u.com熱心網友回復:
您得到的原因Invalid Date是該字串與 dayjs 的決議標記iso8601Format不匹配。dayjs 中的 3 位數毫秒表示為,而不是。此外,dayjs 中的 in 表示與 UTC 的偏移量,如.SSSsssZ-05:00
dayjs(currentDate, iso8601Format, true)是不必要的,因為您可以直接使用dayjs(currentDate). 您還可以傳入 iso8601 格式的字串,dayjs("2022-06-10T04:32:08.320Z")這樣可以正確實體化 dayjs 實體。customParseFormat除非字串只能用決議標記來決議,否則不需要使用。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/491282.html
標籤:javascript 日期 天
