ZombiePie
ZombiePie

Reputation: 379

Get beforeDate using dayjs

How do we get a date before the current date using DayJs.

I know how to get the current date but can we like remove 15 days from the current date?

cy.get('input[name="day"]').should('have.value', (Cypress.dayjs().format('DD')))
cy.get('input[name="month"]').should('have.value', (Cypress.dayjs().format('MM')))
 cy.get('input[name="year"]').should('have.value', (Cypress.dayjs().format('YY'))) ```


This is my code for getting the currentDate. I would like to get 15 days before my current Date. I would have used substract if the date was one input field but here we have different placeholders for the inputs.

Upvotes: 3

Views: 9726

Answers (3)

pavelsaman
pavelsaman

Reputation: 8322

From the documentation:

dayjs().subtract(15, 'day');

Available units are mentioned here, day is one of them.

Upvotes: 7

Michael Hines
Michael Hines

Reputation: 1108

For readable test, calculate target once.

const target = dayjs().subtract(15, 'day')

cy.get('input[name="day"]').should('have.value', target.format('DD'))
cy.get('input[name="month"]').should('have.value', target.format('MM'))
cy.get('input[name="year"]').should('have.value', target .format('YY'))

Upvotes: 0

Alapan Das
Alapan Das

Reputation: 18634

As @pavelsaman mentioned .subtract will work. Yo just have to format it to extract day, month, year.

const dayjs = require('dayjs')

cy.get('input[name="day"]').should(
  'have.value',
  dayjs().subtract(15, 'day').format('DD')
) //11
cy.get('input[name="month"]').should(
  'have.value',
  dayjs().subtract(15, 'day').format('MM')
) //10
cy.get('input[name="year"]').should(
  'have.value',
  dayjs().subtract(15, 'day').format('YY')
) //21

Upvotes: 0

Related Questions