如果您不关心日期组件,那么您应该这样做:
public static DateTime String2SqlAcceptableDateTimeValue( string iso8601DateTimeValue )
{
CultureInfo ci = CultureInfo.InvariantCulture ;
DateTime timestamp ;
bool converted = DateTime.TryParseExact( iso8601DateTimeValue , "yyyy-MM-ddTHH:mm:ss" , ci ,DateTimeStyles.None, out timestamp ) ;
if ( !converted ) throw new ArgumentException("Not an ISO 8601 Date/Time value" , "iso8601DateTimeValue");
DateTime epoch = new DateTime(1900,1,1) ;
DateTime sqlAcceptableValue = epoch + timestamp.TimeOfDay ;
return sqlAcceptableValue ;
}
将日期组件排除在转换为DateTime
. 这使它成为 1-liner(嗯,2-liner):
CultureInfo ci = CultureInfo.InvariantCulture ;
string tod = "0001-01-01T12:34:56".Substring(11) ;
DateTime dtx = new DateTime(1900,1,1) + DateTime.ParseExact(tod,"HH:mm:ss",ci).TimeOfDay ;
我认为这使意图更加清晰;