如何在TypeScript中提取日期的月份缩写与年份?
在TypeScript中提取日期字符串的月份和年份
针对你给出的法语日期格式(如「lun. 1 juil. 2024」),这里提供几种实用的实现方式:
方法1:字符串分割(适合固定格式输入)
如果输入日期的格式完全固定(星期缩写. 日 月份缩写. 年份),可以直接通过字符串分割提取目标部分:
function extractMonthYear(dateStr: string): string { const parts = dateStr.split(' '); // 提取带点的月份并去掉末尾的点 const month = parts[2].replace('.', ''); const year = parts[3]; return `${month} ${year}`; } // 测试示例 console.log(extractMonthYear('lun. 1 juil. 2024')); // 输出 "juil 2024" console.log(extractMonthYear('mar. 15 août. 2023')); // 输出 "août 2023"
方法2:正则表达式(适配更多格式变体)
如果输入日期格式有轻微变化(比如日是两位数),正则表达式能更稳定地匹配月份和年份:
function extractMonthYear(dateStr: string): string { // 匹配带点的月份缩写和后续的四位年份 const match = dateStr.match(/(\w+)\. (\d{4})/); if (!match) { throw new Error('无法解析目标日期格式'); } const month = match[1]; const year = match[2]; return `${month} ${year}`; } // 测试示例 console.log(extractMonthYear('lun. 1 juil. 2024')); // 输出 "juil 2024" console.log(extractMonthYear('ven. 31 déc. 2024')); // 输出 "déc 2024"
方法3:Date对象解析(需注意环境本地化支持)
如果运行环境支持法语本地化日期解析,可以尝试用Date对象处理,但该方法依赖环境配置,兼容性不如前两种:
function extractMonthYear(dateStr: string): string { // 注意:部分环境可能无法直接解析法语日期字符串,需提前验证 const date = new Date(dateStr); if (isNaN(date.getTime())) { throw new Error('无法解析输入的日期'); } // 提取法语月份缩写(去掉点)和年份 const month = date.toLocaleString('fr-FR', { month: 'short' }).replace('.', ''); const year = date.getFullYear().toString(); return `${month} ${year}`; } // 测试示例(需环境支持法语日期解析) console.log(extractMonthYear('lun. 1 juil. 2024')); // 输出 "juil 2024"
注意事项
- 若输入格式固定,字符串分割法实现简单高效;
- 格式有变化时,优先用正则表达式,适配性更强;
- Date对象解析法受运行环境本地化支持限制,使用前需验证环境兼容性。
内容的提问来源于stack exchange,提问作者elokema
相关产品推荐
相关产品推荐

