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

TypeScript日期格式转换异常:期望DD-MM-YYYY却识别为MM-DD-YYYY

当然可以指定日期格式为DD-MM-YYYY来解决这个问题!我来给你几个实用的方案,帮你得到预期的Mar 12 2018结果:

解决方案

1. 手动拆分字符串解析(无需第三方库)

JavaScript/TypeScript的Date构造函数默认会把MM-DD-YYYY格式的字符串当成标准日期解析,但对DD-MM-YYYY的识别会出错。我们可以手动拆分日期字符串,提取日、月、年,再构建正确的Date对象——注意要把月份减1,因为Date的月份是0索引(0对应1月,11对应12月)。

代码示例:

function parseDDMMYYYY(dateStr: string): Date {
  const [day, month, year] = dateStr.split('-').map(Number);
  // 月份减1是关键!
  return new Date(year, month - 1, day);
}

// 测试一下
const input = '12-03-2018';
const correctDate = parseDDMMYYYY(input);
console.log(correctDate.toDateString()); // 输出:Mon Mar 12 2018

2. 结合Intl.DateTimeFormat格式化输出

如果你需要解析后直接输出Mar 12 2018这种格式的字符串,可以用Intl.DateTimeFormat来做格式化,它是浏览器和Node.js原生支持的API,无需额外依赖:

function formatDDMMYYYY(dateStr: string): string {
  const [day, month, year] = dateStr.split('-').map(Number);
  const date = new Date(year, month - 1, day);
  
  return new Intl.DateTimeFormat('en-US', {
    month: 'short', // 输出缩写月份(Mar、Dec等)
    day: '2-digit',
    year: 'numeric'
  }).format(date);
}

console.log(formatDDMMYYYY('12-03-2018')); // 输出:Mar 12 2018

3. 用第三方日期库简化操作(推荐)

如果你的项目已经使用了日期处理库,比如date-fns(轻量无依赖)或者moment.js,直接用库的解析方法指定格式会更省心:

用date-fns的示例:

import { parse, format } from 'date-fns';

const inputDate = '12-03-2018';
// 第二个参数指定输入格式为DD-MM-YYYY
const parsedDate = parse(inputDate, 'dd-MM-yyyy', new Date());
// 输出想要的格式
console.log(format(parsedDate, 'MMM dd yyyy')); // Mar 12 2018

用moment.js的示例:

import moment from 'moment';

const inputDate = '12-03-2018';
const formattedDate = moment(inputDate, 'DD-MM-YYYY').format('MMM DD YYYY');
console.log(formattedDate); // Mar 12 2018

注意事项

尽量避免直接用new Date(dateStr)解析非YYYY-MM-DD或ISO格式的日期,因为不同运行环境的解析行为可能不一致,手动拆分或使用可靠的日期库能避免这类问题。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 09:18:07