javascriptangulardateluxonangular-spectator

Convert yyyyMMdd format to dd/MM/yyyy with Luxon library


I try to parse a date format like '20230701' to '01/07/2023' with Luxon library.

I can do this with the following code:

  toDateFormatDDMMYYYY = DateTime.fromFormat(
    dateFormatToTransform,
    'ddMMyyyy'
  ).toLocaleString(DateTime.DATE_SHORT);

toDateFormatDDMMYYYY has the good format (dd/MM/yyyy) when I console.log(). But this code make my jest spectator test fail:

  it('should transform date to format dd/MM/yyyy when BO format is yyyyMMdd', () => {
    spectator = createPipe(`{{'20201130' | formatDateToddMMyyyy}}`);
    expect(spectator.element).toHaveText('30/11/2020'); // KO returns invalid date
  });

I don’t know if it’s my code or my test that has a problem...

Thanks for your help


Solution

  • You are passing a date string 20201130 that doesn't follow your defined format ddMMyyyy.

    Either you change your format to yyyyMMdd or change the date string to 30112020

    const toDateFormatDDMMYYYY = DateTime.fromFormat(
      dateFormatToTransform,
      'yyyyMMdd'
    ).toLocaleString(DateTime.DATE_SHORT);