在 C# 中有一个强大的 DateTime 类型可以用来将字符串转换为时间日期:
var dt = DateTime.Parse("2022年3月8日");
部分海外站点,如英国或美国会输出包含缩写月份的时间日期字符串:
8 Sept. 2021
如果尝试对其进行转换,则会报错:
var dt = DateTime.Parse("8 Sept. 2021");
The string ‘8 Sept. 2021’ was not cognized as a valid DateTime. The is an unknown word starting at index ‘2’.
报错信息
根据百度知道的信息:
September的缩写用Sept.或Sep.均可。September是特殊的,只有它一个是前4个字母,其它都是3个字母。
来自:百度知道
如果将 Sept. 更换为 Sep. ,则转换可以正常进行。这说明 .NET 类库仅支持了 Sep. 但并未支持 Sept. 。要解决该问题,只需将缩写还原即可:
public static DateTime ToDateTime(string str){ /* * * 除九月的英文缩写是前四个字母Sept,其他的都是英文全称的前三位,如十一月缩写为 Nov . 十二月为 Dec. * 一月:January 。英文缩写:Jan. * 二月:February。英文缩写:Feb. * 三月 :March 。英文缩写:Mar. * 四月:April。英文缩写:Apr. * 五月:May。英文缩写:May. * 六月:June。英文缩写:Jun. * 七月:July。英文缩写:Jul. * 八月:August。英文缩写:Aug. * 九月:September。英文缩写:Sept. * 十月:October。英文缩写:Oct. */ var fmt = str .place(" Jan. ", " January ") .place(" Feb. ", " February ") .place(" Mar. ", " March ") .place(" Apr. ", " April ") .place(" May. ", " May ") .place(" Jun. ", " June ") .place(" Jul. ", " July ") .place(" Aug. ", " August ") .place(" Sep. ", " September ") .place(" Sept. ", " September ") .place(" Oct. ", " October ") .place(" Nov. ", " November ") .place(" Dec. ", " December ") .Trim(); turn DateTime.Parse(fmt);}