日历开发:如何将日期输出格式改为dd/Month/yyyy分隔形式?
解决方案
直接在现有thisDate函数里添加格式化逻辑是更合适的选择——输入框属性通常用于控制显示样式或输入校验,不适合处理这种字符串格式化的业务逻辑。
具体修改步骤如下:
- 新增日期字符串格式化的辅助逻辑,把无分隔符的日期(比如
15February2023)替换成带斜杠的格式; - 用格式化后的日期拼接最终显示内容;
- 注意你代码里的
date.firstDay = new Date().toLocaleDateString();和date.lastDay = new Date().toLocaleDateString();是覆盖用户选择日期的测试代码,应该删掉。
修改后的代码:
methods: { thisDate(date) { // 格式化日期字符串:添加斜杠分隔日/月/年 const formatDateStr = (dateStr) => { // 匹配 数字(日)+字母(月)+数字(年) 的格式,分组替换 return dateStr.replace(/^(\d+)([A-Za-z]+)(\d+)$/, '$1/$2/$3'); }; // 用格式化后的日期拼接结果 this.date = `${formatDateStr(date.firstDay)} - ${formatDateStr(date.lastDay)}`; // 删掉下面两行测试代码,避免覆盖用户选择的日期 // date.firstDay = new Date().toLocaleDateString(); // date.lastDay = new Date().toLocaleDateString(); console.log(date.lastDay); } }
如果你的date.firstDay和date.lastDay其实是Date对象(而非字符串),可以直接用toLocaleDateString指定参数生成带斜杠的月份全称格式,示例如下:
const formatDateObj = (dateObj) => { return dateObj.toLocaleDateString('en-US', { day: 'numeric', month: 'long', year: 'numeric' }).replace(/ /g, '/'); };
将上面的formatDateStr替换为这个formatDateObj即可。
内容的提问来源于stack exchange,提问作者Fonteyn Atlas
相关产品推荐
相关产品推荐

