写了一个根据传入日期查询日期对应的当月数据的功能:
const getDate = () => {
const date = '2023-04-01';
const year = new Date(date).getFullYear();
const month = new Date(date).getMonth();
const maxDate = new Date(month === 11 ? `${year + 1}-01-01` : `${year}-${month + 2}-01`);
const minDate = new Date(`${year}-${month + 1}-01`);
console.log('minDate', minDate, minDate.getTime());
console.log('maxDate', maxDate, maxDate.getTime());
}
getDate()
问题:
h5页面在微信中打开与在浏览器上打开执行结果不一致
原因:微信中getTime()返回NaN,没有成功转换成时间戳,比较数据格式发现月份没有补0,导致转换失败
正确示例:
const getDate = () => {
const date = '2023-04-01';
const year = new Date(date).getFullYear();
const month = new Date(date).getMonth();
const maxDate = new Date(month === 11 ? `${year + 1}-01-01` : `${year}-${(month + 2 + '').padStart(2, '0')}-01`);
const minDate = new Date(`${year}-${(month + 1 + '').padStart(2, '0')}-01`);
console.log('minDate', minDate, minDate.getTime());
console.log('maxDate', maxDate, maxDate.getTime());
}
getDate()
总结:字符串转时间戳时,'2023-04-01'和'2023-4-1'在微信中不能正确转换,即使在浏览器中转换结果也不一致,直接格式化字符串为'2023-04-01'