You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Cypress中newDate转为YYYY-MM-DD格式以匹配输入框值?

解决Cypress日期输入框格式匹配问题

你遇到的问题是因为new Date()生成的默认日期字符串格式和输入框的YYYY-MM-DD不匹配,导致断言失败。只需要把日期格式化为指定的YYYY-MM-DD格式即可,下面提供两种简单的修改方式:

方法一:手动拼接格式化日期

通过Date对象的方法获取年、月、日,手动拼接成目标格式(注意月份是从0开始计数,需要加1,并且用padStart(2, '0')补零保证两位数):

cy.window().then((win) => {
  const currentDate = new Date(win.Date());
  const year = currentDate.getFullYear();
  const month = String(currentDate.getMonth() + 1).padStart(2, '0');
  const day = String(currentDate.getDate()).padStart(2, '0');
  const formattedDate = `${year}-${month}-${day}`;
  
  cy.get('#datefrom').should('be.visible').and('have.value', formattedDate);
});

方法二:利用toISOString()快速截取

toISOString()方法会返回类似2023-04-05T15:50:37.000Z的字符串,直接截取前10位就能得到YYYY-MM-DD格式:

cy.window().then((win) => {
  const formattedDate = new Date(win.Date()).toISOString().slice(0, 10);
  cy.get('#datefrom').should('be.visible').and('have.value', formattedDate);
});

这两种方式都能生成和输入框一致的日期格式,解决断言报错的问题。

内容的提问来源于stack exchange,提问作者Michelle Murray

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 05:07:16