Well, you could probably do something like this, using the K
format specifier (see Custom DateTime Format Strings for details):
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" ,
} ;
But you'll probably find something like this somewhat more performant:
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 ;
}
Though, I'm sure there's some oddities around dealing with the time zone/offset-from-UTC that I haven't properly considered and would have to be properly dealt with.