Home > OS >  Format custom date using dayjs without using CustomParseFormat
Format custom date using dayjs without using CustomParseFormat

Time:06-10

I am currently working on migrating from momentjs to dayjs.

The part that I’m stuck on is that converting an Dayjs object with ISO8601 under strict mode as momentjs does. At first, I tried to convert the object with CustomParseFormat like below as a documentation described. And it returned invalid date object like below because of issue from a bug in 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
// }

However, if I converted the object without extending CustomParseFormat, it seems like returning an valid object.

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
// }

So, my question is that does dayjs allow to parse the date with custom format without using CustomParseFormat? Also, does it guarantee that the result is same as momentjs? Thanks.

CodePudding user response:

The reason why you are getting Invalid Date is because the iso8601Format string does not match dayjs's parsing tokens. 3-digit milliseconds in dayjs is represented as SSS, not sss. In addition, the Z in dayjs represents offset from UTC, as -05:00.

dayjs(currentDate, iso8601Format, true) is unnecessary as you can instantiate a dayjs instance directly with dayjs(currentDate). You can also pass in a string in iso8601format like dayjs("2022-06-10T04:32:08.320Z") and that will correctly instantiate a dayjs instance. There is no need to use customParseFormat unless the string can only be parsed with the parsing tokens.

  • Related