iamkun / dayjs

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

Parsing with format object parameter doesn't work #1285

Open cypressious opened 3 years ago

cypressious commented 3 years ago

Describe the bug I'm using the following plugins:

import * as customParseFormat from 'dayjs/plugin/customParseFormat';
import * as weekday from 'dayjs/plugin/weekday';
import * as localizedFormat from 'dayjs/plugin/localizedFormat';
import * as DAYJS_LOCALE_DE from 'dayjs/locale/de';

dayjs.extend(customParseFormat);
dayjs.extend(weekday);
dayjs.extend(localizedFormat);
dayjs.locale(DAYJS_LOCALE_DE);

The TypeScript declarations (extract below) suggest that the dayjs() function accepts the second parameter in the object form { locale?: string, format?: string, utc?: boolean }.

declare function dayjs (date?: dayjs.ConfigType): dayjs.Dayjs
declare function dayjs (date?: dayjs.ConfigType, format?: dayjs.OptionType, strict?: boolean): dayjs.Dayjs
declare function dayjs (date?: dayjs.ConfigType, format?: dayjs.OptionType, locale?: string, strict?: boolean): dayjs.Dayjs

declare namespace dayjs {
  export type ConfigType = string | number | Date | Dayjs
  export type OptionType = { locale?: string, format?: string, utc?: boolean } | string | string[]
  ...
}

However, calling dayjs('8. Dez 2020 15:22', { format: 'D. MMM YYYY HH:mm'}) returns an invalid date whereas dayjs('8. Dez 2020 15:22', 'D. MMM YYYY HH:mm') returns a parsed date.

Expected behavior Calling dayjs('8. Dez 2020 15:22', { format: 'D. MMM YYYY HH:mm'}) returns a parsed date.

Information

iamkun commented 3 years ago

dayjs('8. Dez 2020 15:22', { format: 'D. MMM YYYY HH:mm'}) is not listed on the doc.

please use dayjs('8. Dez 2020 15:22', 'D. MMM YYYY HH:mm') instead

cypressious commented 3 years ago

Shouldn't it be removed from the type definitions then?

patgod85 commented 1 year ago

I just stumbled upon the issue.

import dayjs from 'dayjs';
import dayJsCustomParseFormat from 'dayjs/plugin/customParseFormat';

describe('Dates parsing', () => {
    beforeAll(() => {
        dayjs.extend(dayJsCustomParseFormat);
    });

    it('should parse equally', () => {
        const result1 = dayjs('08.04.2011', 'DD.MM.YYYY');
        const result2 = dayjs('08.04.2011', { format: 'DD.MM.YYYY' });

        expect(result1).toEqual(result2);
// - Expected  - 1
// + Received  + 1

// - "2011-08-03T20:00:00.000Z"
// + "2011-04-07T20:00:00.000Z"
    });
});

What if I also need to pass utc: true with format? I don't see the way to do it without using OptionType as an object.