无法从'M / yy / d'确定年,月和日的顺序

问题描述 投票:1回答:2

当我跑: 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)。

.net parsing datetime formatting date-format
2个回答
2
投票

问题是两个组成部分的结果:

  1. 您当前的文化使用与不变文化默认值(/)不同的日期分隔符。
  2. /用作DateTime.ParseDateTime.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
投票

旧问题,但代码已过时。接受的答案详细说明了为什么会发生这种情况+1的原因。

DateTime.ParseExact("11/11/1997", "MM/dd/yyyy", null, System.Globalization.DateTimeStyles.None);
© www.soinside.com 2019 - 2024. All rights reserved.