-4

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

  • In the USA, `11/04/2023` is November 4th, 2023. Does dayjs recognize locales? – Kosh Mar 31 '23 at 17:29
  • 2
    There is no difference between the expected format and the actual format. Both are `DD-MMM-YYYY`. – jabaa Mar 31 '23 at 17:40

2 Answers2

3

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')
})
0

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

agoff
  • 5,818
  • 1
  • 7
  • 20