使用 dayjs 获取 beforeDate

Get beforeDate using dayjs

我们如何使用 DayJs 获取当前日期之前的日期。

我知道如何获取当前日期,但我们可以从当前日期中删除 15 天吗?

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.

来自documentation

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

提到了可用单位 hereday 是其中之一。

正如@pavelsaman 提到的那样,.subtract 会起作用。你只需要格式化它来提取日,月,年。

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

对于可读性测试,计算一次目标。

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