我正在尝试使用以下内容解析DateTime字符串“ 5-5-5-5”
DateTime.TryParse("5-5-5-5", CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out result);
我希望这可以转换为
5/5/2005 5:00:00 AM
但是相反,它被转换为
5/5/2005 10:30:00 AM.
看起来像它将提供的日期时间解释为GMT。因为我已经指定了AssumeLocal
标志,所以这有点违反直觉。这是DateTime
班上的错误吗?
我理解您的观点并调试点网框架代码以了解后台发生的情况。
TryParse
方法将忽略DateTimeStyles.AssumeLocal
标志,并且仅AdjustToUniversal
处理标志。
if ((styles & DateTimeStyles.AdjustToUniversal) != 0) {
return (AdjustTimeZoneToUniversal(ref result));
}
return (AdjustTimeZoneToLocal(ref result, bTimeOnly));
另一方面,
TryParseExact
方法已正确实现,并且具有处理DateTimeStyles.AssumeLocal
标志所需的所有逻辑。查看此实现中如何处理其他情况。
// If AssumeLocal or AssumeLocal is used, there will always be a kind specified. As in the
// case when a time zone is present, it will default to being local unless AdjustToUniversal
// is present. These comparisons determine whether setting the kind is sufficient, or if a
// time zone adjustment is required. For consistentcy with the rest of parsing, it is desirable
// to fall through to the Adjust methods below, so that there is consist handling of boundary
// cases like wrapping around on time-only dates and temporarily allowing an adjusted date
// to exceed DateTime.MaxValue
if ((styles & DateTimeStyles.AssumeLocal) != 0) {
if ((styles & DateTimeStyles.AdjustToUniversal) != 0) {
result.flags |= ParseFlags.TimeZoneUsed;
result.timeZoneOffset = TimeZoneInfo.GetLocalUtcOffset(result.parsedDate, TimeZoneInfoOptions.NoThrowOnInvalidTime);
}
else {
result.parsedDate = DateTime.SpecifyKind(result.parsedDate, DateTimeKind.Local);
return true;
}
}
else if ((styles & DateTimeStyles.AssumeUniversal) != 0) {
if ((styles & DateTimeStyles.AdjustToUniversal) != 0) {
result.parsedDate = DateTime.SpecifyKind(result.parsedDate, DateTimeKind.Utc);
return true;
}
else {
result.flags |= ParseFlags.TimeZoneUsed;
result.timeZoneOffset = TimeSpan.Zero;
}
}
else {
// No time zone and no Assume flags, so DateTimeKind.Unspecified is fine
Contract.Assert(result.parsedDate.Kind == DateTimeKind.Unspecified, "result.parsedDate.Kind == DateTimeKind.Unspecified");
return true;
}
附带说明,调试Dot Net框架代码很有趣。如果您有兴趣,请从这里开始。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句