skip to Main Content

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

2

Answers


  1. 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

    Login or Signup to reply.
  2. A better library is date-fns. It will tell you in the test when you get the format wrong.

    import {parse, format} from 'date-fns'
    
    it('tests date parsing and formatting', () => {
    
      const text = 'Extension date: 11/04/2023'
      const datePart = text.split(':')[1].trim()
    
      const myDate = parse(datePart, 'dd/MM/yyyy', new Date())
      const formatted = format(myDate, 'dd MMM yyyy')
      
      expect(formatted).to.eq('11 Apr 2023')
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search