Search code examples
javascriptcypressdayjscypress-dayjs

How to convert date into my required format using dayjs module


I am reading a date from a locator through cypress the actual date is 11/04/2023

cy.get("#eff-date").invoke('text').then(()=>{
const edate = dayjs(text.split(':')[1].format('DD-MMM-YYYY'))
})

What it is returning

04-Nov-2023

But it should be 11-Apr-2023


Solution

  • You're attempting to parse a non-ISO 8601 date string. According to the dayjs docs:

    For consistent results parsing anything other than ISO 8601 strings, you should use String + Format.

    The following should work.

    var customParseFormat = require('dayjs/plugin/customParseFormat')
    dayjs.extend(customParseFormat)
    ...
    cy.get("#eff-date")
      .invoke('text')
      .then(()=>{
        // Have to pass the custom parsing format, which is MM and not MMM
        const edate = dayjs(text.split(':')[1], 'DD-MM-YYYY');
        // To display, we have to use dayjs.format()
        console.log(edate.format('DD-MMM-YYYY');
    })
    

    More information on using the String + Format (and customParseFormat) here