当我们在vant中使用DatePicker日期选择器时,v-model绑定值默认是一个数组,如果我们需要展示日期的字符串,那么就需要进行转换。日期的选项类型由 year
、month
和 day
组成,可通过columns-type属性改变选项类型,因此数组的长度是不固定的,下面两个方法实现了数组和字符串之间来回转换。
1. 将 "2024年06月04日" 转化为 [2024, 6, 4]
parseDateToArray(dateString){
// 初始化结果数组,默认为三个空字符串
const result = ['', '', ''];
// 使用正则表达式匹配年份、月份和日期
const yearMatch = dateString.match(/(\d{4})年/);
const monthMatch = dateString.match(/(\d{2})月/);
const dayMatch = dateString.match(/(\d{2})日/);
// 填充结果数组
if (yearMatch) {
result[0] = parseInt(yearMatch[1], 10); // 将年份转换为数字
}
if (monthMatch) {
result[1] = parseInt(monthMatch[1], 10); // 将月份转换为数字
}
if (dayMatch) {
result[2] = parseInt(dayMatch[1], 10); // 将日期转换为数字
}
return result.filter(item => item !== '');
}
2. 将 [20