在 DateTime.ParseExact 格式化方面遇到问题时,我决定将 DateTime.ToString() 的输出作为 ParseExact 的输入,像这样:
DateTime date2 = new DateTime(1962, 1, 27);
string[] expectedFormats = { "G", "g", "f", "F", "D", "d", "M/d/yyy", "MM/dd/yyy", "MM-dd-yyy", "MMM dd, yyy", "MMM dd yyy", "MMMM dd, yyy", "MMMM dd yyy" };
bool parsed = false;
foreach (string fmt in expectedFormats)
{
try
{
DateTime dtDateTime = DateTime.ParseExact(date2.ToString(fmt), fmt, new CultureInfo("en-US"));
parsed = true;
}
catch (Exception)
{
parsed = false;
}
Console.WriteLine("[{0}] {1}", parsed,date2.ToString(fmt));
}
这是输出结果:
[True] 1/27/1962 12:00:00 AM
[True] 1/27/1962 12:00 AM
[True] Saturday, January 27, 1962 12:00 AM
[True] Saturday, January 27, 1962 12:00:00 AM
[True] Saturday, January 27, 1962
[True] 1/27/1962
[False] 1/27/1962
[False] 01/27/1962
[False] 01-27-1962
[False] Jan 27, 1962
[False] Jan 27 1962
[False] January 27, 1962
[False] January 27 1962
我需要做什么才能使ParseExact解析自定义格式的字符串?我是否期望DateTime能够基于相同的格式字符串摄入它自己的输出?
CultureInfo.InvariantCulture
,但没有成功。 - Brian Gideon