简体   繁体   English

DateTime.Parse String 未被识别为有效的 DateTime

[英]DateTime.Parse String was not recognized as a valid DateTime

Code has been simplified for ease of asking question, string is pulled from an array and has been verified to be exactly as provided below.为了便于提问,代码已经过简化,字符串是从数组中提取的,并且已经过验证与下面提供的完全一致。 The below code results in error:以下代码导致错误:

Message: "String was not recognized as a valid DateTime."消息:“字符串未被识别为有效的日期时间。”

string myDate = "20221215.08.14.01.37";
DateTime dt = DateTime.Parse(myDate);

I was expecting the string to be converted to DateTime, have tried working with other DateTime methods such as TryParse, and providing formatting, without success.我期待将字符串转换为 DateTime,尝试使用其他 DateTime 方法(例如 TryParse)并提供格式设置,但没有成功。

This is unusual format so Parse cannot handle that.这是不寻常的格式,因此Parse无法处理。 You have to use DateTime.ParseExact :您必须使用DateTime.ParseExact

DateTime.ParseExact(myDate, "yyyyMMdd.HH.mm.ss.ff", CultureInfo.InvariantCulture);

See more info about format specifiers here . 在此处查看有关格式说明符的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM