解析在C#中的DateTimeOffset字符串 [英] Parsing a DateTimeOffset string in C#
问题描述
我需要从多种格式的字符串解析datetimeoffsets。一个失败的字符串是:
1992年8月12日07.00.00 -05:00
现在,当我尝试解析此,我使用:
<预类=郎-CS prettyprint-覆盖>
DateTimeOffset.ParseExact(1992年8月12日07.00.00 -05:00, DD / MM / YYYY HH:MM:SS ZZZ,CultureInfo.InvariantCulture)
这给 FormatException
:
字符串未被识别为有效的DateTime。
块引用>
我也可以尝试在分隔符添加分隔符:
<预类=郎-CS prettyprint-覆盖>DateTimeOffset.ParseExact(1992年8月12日07.00.00 -05:00,DD'/'MM'/'YYYY HH ':'毫米':'SS ZZZ,CultureInfo.InvariantCulture)
...或其他排列小/大写字母或分离器,但我得到了同样的错误。
谁能告诉我,为什么ParseExact线以上不工作,以及如何纠正呢?
编辑:我试着使用LINQ查询,以取代点冒号(: - >)。显然,这并不能正常工作 - 感谢您的答复。
解决方案您实际日期(实际时间)的字符串分隔从小时从秒分钟,点
,让您的格式必须做同样的:
DateTimeOffset.ParseExact(1992年8月12日07.00.00 -05:00,
DD / MM / YYYY HH.MM.SS ZZZ,CultureInfo.InvariantCulture)
/ / ^^
// | |
如果您有多个字符串格式的数据,你可以做这样的事情:
公共静态的DateTimeOffset解析(字符串str)
{
的String []格式=
{
DD / MM / YYYY HH.MM.SS ZZZ,
DD / MM / YYYY HH:MM:SS ZZZ
// ...可能更多...
};
变种DTO =新的DateTimeOffset();如果
(formats.Any(F =>!DateTimeOffset.TryParseExact(STR,F CultureInfo.InvariantCulture,DateTimeStyles.None,出DTO)))
{
抛出新的ArgumentException(无法识别的日期格式);
}
返回DTO;
}
I need parse datetimeoffsets from strings of multiple formats. One of the strings that fail is: 08/12/1992 07.00.00 -05:00
Now when I try to parse this, I use:
DateTimeOffset.ParseExact("08/12/1992 07.00.00 -05:00", "dd/MM/yyyy HH:mm:ss zzz", CultureInfo.InvariantCulture)
Which gives a
FormatException
:"String was not recognized as a valid DateTime."
I can also try to add delimiters in the separators:
DateTimeOffset.ParseExact("08/12/1992 07.00.00 -05:00", "dd'/'MM'/'yyyy HH':'mm':'ss zzz", CultureInfo.InvariantCulture)
...or other permutations of small/capital letter or separators, but I get the same error.
Can anyone tell me why the ParseExact lines above do not work, and how to correct them?
EDIT: I tried using a LINQ query to replace the colon with dots (: -> .). Apparently that did not work correctly - thanks for the replies.
解决方案Your actual date (actually time) string delimits the hours from the minutes from the seconds with a dot
.
, so your format must do the same:DateTimeOffset.ParseExact("08/12/1992 07.00.00 -05:00", "dd/MM/yyyy HH.mm.ss zzz", CultureInfo.InvariantCulture) // ^ ^ // | |
If you have multiple string formats in your data, you can do something like this:
public static DateTimeOffset Parse(string str) { string[] formats = { "dd/MM/yyyy HH.mm.ss zzz", "dd/MM/yyyy HH:mm:ss zzz" // ... possibly more ... }; var dto = new DateTimeOffset(); if (!formats.Any(f => DateTimeOffset.TryParseExact(str, f, CultureInfo.InvariantCulture, DateTimeStyles.None, out dto))) { throw new ArgumentException("Unrecognized date format"); } return dto; }
这篇关于解析在C#中的DateTimeOffset字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!