当我跑:
Date.Parse(Now.ToString("M/yy/d"), New Globalization.DateTimeFormatInfo() With {.ShortDatePattern = "M/yy/d"})
我收到错误:
Could not determine the order of year, month, and date from 'M/yy/d'.
这个(奇怪的)格式是禁止的吗?这是一个错误吗?
注意 我不知道为什么需要这种格式。
编辑
拟议的Date.ParseExact(Now.ToString("M/yy/d"), "M/yy/d",New Globalization.DateTimeFormatInfo() )
给出:
String was not recognized as a valid DateTime.
EDIT2 我正在使用.NET Framework 4.0(Windows)。
问题是两个组成部分的结果:
/
)不同的日期分隔符。/
用作DateTime.Parse
或DateTime.ParseExact
格式字符串的一部分时,它是not translated as a literal forward slash,而是指定格式提供者的日期分隔符,无论是什么(如果你想要从字面上理解,你必须使用“转义序列” “%/
)。所以有很多方法可以正确地做到这一点:
Date.ParseExact(Now.ToString("M/yy/d"), "M%/yy%/d", Nothing)
这只是告诉ParseExact
从字面上解释斜杠。
Date.ParseExact(Now.ToString("M/yy/d"), "M/yy/d",
New Globalization.DateTimeFormatInfo() With {.DateSeparator = "/"})
这告诉ParseExact
使用文字斜杠作为日期分隔符,更改其当前文化的默认行为。
顺便说一句:我使用ParseExact
而不是Parse
,因为当你知道输入具有特定的格式时,它更适合; Parse
尝试使用启发式方法自行确定格式,这在这种情况下是不合适的。
旧问题,但代码已过时。接受的答案详细说明了为什么会发生这种情况+1的原因。
DateTime.ParseExact("11/11/1997", "MM/dd/yyyy", null, System.Globalization.DateTimeStyles.None);