简体   繁体   English

将结果字符串日期时间转换为日期时间值

[英]convert resulting string datetime to dateTime value

i am fetching datetime value through xml like:我正在通过 xml 获取日期时间值,例如:

string time = "20150605020247+0000"

I want to convert into datetime value.我想转换为日期时间值。 I tried with DateTime.Parse , ParseExact , Convert.ToDateTime .我尝试了DateTime.ParseParseExactConvert.ToDateTime It's not working, it's returning the error:它不起作用,它返回错误:

string was not recognised as valid datetime字符串未被识别为有效的日期时间

You should be able to use DateTime.ParseExact , since you know the exact format of the string.您应该能够使用DateTime.ParseExact ,因为您知道字符串的确切格式。 If we assume it's year, month, day, hour, minute, second, and offset, then you can do something like:如果我们假设它是年、月、日、小时、分钟、秒和偏移量,那么您可以执行以下操作:

var result = DateTime.ParseExact("20150605020247+0000", "yyyyMMddHHmmsszzz", 
    CultureInfo.InvariantCulture);

你应该像这样使用DateTime.ParseExact

DateTime theTime = DateTime.ParseExact(time,  "ddMMyyyyHHmmss+ffff,CultureInfo.InvariantCulture);

You need to use exact format specifier in your ParseExact method.您需要在 ParseExact 方法中使用精确格式说明符。

DateTime.ParseExact("20150605020247+0000", "yyyyMMddHHmmsszzz", System.Globalization.CultureInfo.InvariantCulture);

Fiddle: https://dotnetfiddle.net/cQJ9hN小提琴: https : //dotnetfiddle.net/cQJ9hN

EDIT:编辑:

Please check the standard DateTime formats used in .NET world: https://docs.microsoft.com/en-us/dotnet/standard/base-types/standard-date-and-time-format-strings plus check the source of your data how exactly are the string dates produced.请检查 .NET 世界中使用的标准日期时间格式: https : //docs.microsoft.com/en-us/dotnet/standard/base-types/standard-date-and-time-format-strings并检查源您的数据字符串日期究竟是如何产生的。 However most likely the '+####' part of your string is the local date UTC offset , not the fractions part of the time (as other answers suggest).但是,很可能字符串的 '+####' 部分是本地日期 UTC offset ,而不是时间的小数部分(如其他答案所建议的那样)。 So parsing the date by using the "yyyyMMddhhmmssffff" would produce wrong results .因此,使用“yyyyMMddhhmmssffff”解析日期会产生错误的结果

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

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