如何在Windows批处理文件中将短日期(如Dec17)转换为长日期?
嘿,这个需求我刚好处理过类似的场景,用Windows批处理完全能搞定!核心就是先建立月份缩写到全称的映射,再拆分并转换年份部分。下面是完整的实现方案,你可以直接用或者根据自己的需求调整:
Windows批处理日期缩写转换脚本
基础版(单个日期转换)
这个脚本可以处理单个输入日期,比如把Dec17转成December2017:
@echo off setlocal enabledelayedexpansion :: 定义所有月份缩写到全称的映射 set "Jan=January" set "Feb=February" set "Mar=March" set "Apr=April" set "May=May" set "Jun=June" set "Jul=July" set "Aug=August" set "Sep=September" set "Oct=October" set "Nov=November" set "Dec=December" :: 这里可以手动指定输入日期,或者用命令行参数(注释掉下面一行,启用下一行) set "inputDate=Dec17" :: set "inputDate=%~1" // 启用后,运行脚本时传入参数:convertDate.bat Jul18 :: 拆分月份缩写和两位年份 set "monthAbbr=!inputDate:~0,3!" set "year2=!inputDate:~3!" :: 转换为完整月份和四位年份 set "fullMonth=!%monthAbbr%!" set "fullYear=20%year2%" // 默认年份为20xx,如需支持19xx看下面的扩展 :: 拼接最终结果 set "fullDate=!fullMonth!!fullYear!" echo 输入: %inputDate% echo 输出: !fullDate! endlocal
关键逻辑解释
setlocal enabledelayedexpansion:必须开启这个,才能在变量动态变化时正确读取值- 月份映射:把每个三位月份缩写对应到全称,确保覆盖12个月份,拼写别出错哦
- 字符串拆分:用
!inputDate:~0,3!提取前3位作为月份缩写,!inputDate:~3!提取剩下的两位年份 - 间接变量引用:
!%monthAbbr%!是核心技巧,比如当monthAbbr是Dec时,会自动获取Dec变量的值December
扩展版(批量处理+年份兼容19xx)
如果需要批量处理文件里的日期,或者要兼容19xx的年份,可以用这个版本:
@echo off setlocal enabledelayedexpansion :: 月份映射不变 set "Jan=January" set "Feb=February" set "Mar=March" set "Apr=April" set "May=May" set "Jun=June" set "Jul=July" set "Aug=August" set "Sep=September" set "Oct=October" set "Nov=November" set "Dec=December" :: 读取dates.txt中的每行日期(每行一个,比如Dec17、Jul18) for /f "delims=" %%d in (dates.txt) do ( set "inputDate=%%d" set "monthAbbr=!inputDate:~0,3!" set "year2=!inputDate:~3!" :: 判断年份,比如大于50的视为19xx,否则20xx if !year2! gtr 50 ( set "fullYear=19%year2%" ) else ( set "fullYear=20%year2%" ) set "fullMonth=!%monthAbbr%!" set "fullDate=!fullMonth!!fullYear!" echo 输入: !inputDate! -> 输出: !fullDate! ) endlocal
注意事项
- 确保输入的日期格式严格是三位月份缩写+两位年份,不要有空格或其他多余字符
- 如果需要处理其他格式的日期,比如小写缩写(dec17),可以先把输入转成全大写:
set "inputDate=!inputDate:~0,3!!inputDate:~3!",或者把映射里的缩写也改成小写
内容的提问来源于stack exchange,提问作者Samuel Finny
相关产品推荐
相关产品推荐

