我试图将string
转换为DateTime
。但我无法转换。无法在Windows Phone 7中解析字符串DateTime
DateTime dt = DateTime.Parse("16/11/2014", CultureInfo.InvariantCulture);
Console.WriteLine("Date==> " + dt);
错误是FormatException
。
我的输入时间格式为"dd/MM/yyyy"
。
请让我任何想法来解决我的问题。
我试图将string
转换为DateTime
。但我无法转换。无法在Windows Phone 7中解析字符串DateTime
DateTime dt = DateTime.Parse("16/11/2014", CultureInfo.InvariantCulture);
Console.WriteLine("Date==> " + dt);
错误是FormatException
。
我的输入时间格式为"dd/MM/yyyy"
。
请让我任何想法来解决我的问题。
因为InvariantCulture
不具有dd/MM/yyyy
作为标准日期和时间格式,但它具有MM/dd/yyyy
作为标准日期和时间格式。
这就是为什么它认为你的字符串是MM/dd/yyyy
格式,但因为没有16
as a month in Gregorian calender,所以你得到了FormatException
。
取而代之的是,您可以使用DateTime.TryParseExact
方法指定确切的格式,如;
string s = "16/11/2014";
DateTime dt;
if(DateTime.TryParseExact(s, "dd/MM/yyyy", CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
}
既然你知道你的输入格式,你应该用'ParseExact指定:
DateTime dt = DateTime.ParseExact(text, "dd/MM/yyyy",
CultureInfo.InvariantCulture);
我总是建议是为明确的,你可以约日期/时间格式。它使你的意图非常清楚,并避免了错误的方式获取数月和数天的可能性。
由于Soner曾表示,CultureInfo.InvariantCulture
使用MM/dd/yyyy
作为其短日期模式,你可以验证:
Console.WriteLine(CultureInfo.InvariantCulture.DateTimeFormat.ShortDatePattern)
作为一个温和的插件,你可能想用我的Noda Time项目的日期考虑 /时间处理 - 除了其他任何东西,它允许你把日期当作日期,而不是日期和时间......
感谢您的回答和解释..您和Soner解释国家是超级..谢谢.. – 2014-12-09 13:50:04
谢谢..它的工作..和解释是超..再次感谢。 – 2014-12-09 13:07:52