gpt4 book ai didi

c# - 如何在 C# 中解析一种未知的日期时间格式

转载 作者:太空宇宙 更新时间:2023-11-03 10:45:54 33 4
gpt4 key购买 nike

我正在尝试为 TV Schedule Pro ( http://sourceforge.net/p/tvschedulerpro ) 编写一个 XML 解析器。一个特殊的挑战是解析日期元素报告的日期时间。

根据DTD文件:

All dates and times in this DTD follow the same format, loosely based on ISO 8601. They can be 'YYYYMMDDhhmmss' or some initial substring, for example if you only know the year and month you can have 'YYYYMM'. You can also append a timezone to the end; if no explicit timezone is given, UTC is assumed. Examples: '200007281733 BST', '200209', '19880523083000 +0300'. (BST == +0100.)

这是一个具有挑战性的情况,我最初考虑使用 DateTimeFormatInfo.GetAllDateTimePatterns 并使用 DateTime.TryParseExact,最后一行关于时区和带有任何分隔符的特定格式使得无法使用上述内容。

是否有一种简洁的方法来解析上述日期时间规范,或者是否只需要不断查找/添加各种模式以在找到它们时解析字符串(看起来几乎是无穷无尽的组合)

最佳答案

好吧,您可以使用 K 格式说明符(有关详细信息,请参阅自定义日期时间格式字符串)做这样的事情:

public static DateTimeOffset parseIso8601CompactForm( string text )
{
DateTimeStyles options = DateTimeStyles.AllowWhiteSpaces
| DateTimeStyles.AssumeLocal
;
DateTimeOffset value = DateTimeOffset.ParseExact( text , formats , CultureInfo.CurrentCulture , options ) ;
return value ;
}
static readonly string[] formats =
{
"yyyyMMddHHmmssK" , "yyyyMMddHHmmss" ,
"yyyyMMddHHmmK" , "yyyyMMddHHmm" ,
"yyyyMMddHHK" , "yyyyMMddHH" ,
"yyyyMMddK" , "yyyyMMdd" ,
"yyyyMMK" , "yyyyMM" ,
"yyyyK" , "yyyy" ,
} ;

但您可能会发现类似这样的性能更高:

public static DateTimeOffset parseIso8601CompactForm( string text )
{
if ( string.IsNullOrEmpty(text) ) throw new ArgumentException("text") ;
if ( string.Length < 4 ) throw new ArgumentException("text") ;

int YYYY = text.Length >= 4 ? int.Parse(text.Substring( 0 , 4 ) ) : 1 ;
int MM = text.Length >= 6 ? int.Parse(text.Substring( 4 , 2 ) ) : 1 ;
int DD = text.Length >= 8 ? int.Parse(text.Substring( 6 , 2 ) ) : 1 ;
int hh = text.Length >= 10 ? int.Parse(text.Substring( 8 , 2 ) ) : 0 ;
int mm = text.Length >= 12 ? int.Parse(text.Substring( 10 , 2 ) ) : 0 ;
int ss = text.Length >= 14 ? int.Parse(text.Substring( 12 , 2 ) ) : 0 ;
string tzid = text.Length > 14 ? text.Substring(14).Trim() : null ;
TimeZoneInfo tz = TimeZoneInfo.FindSystemTimeZoneById( tzid ) ;
DateTimeOffset value = new DateTimeOffset( YYYY , MM , DD , hh , mm , ss , tz.BaseUtcOffset ) ;
return value ;
}

不过,我确信在处理时区/UTC 偏移量方面存在一些奇怪的地方,我没有正确考虑这些问题,必须妥善处理。

关于c# - 如何在 C# 中解析一种未知的日期时间格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23434184/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com