Skip to main content
 首页 » 编程设计

c#之DateTime.TryParse 中的奇怪行为

2024年02月06日15bluestorm

我正在尝试用

解析日期时间字符串“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 类中的错误吗?

请您参考如下方法:

我理解您的意思并调试 dot net 框架代码以了解后台发生的情况。

TryParse method is ignoring DateTimeStyles.AssumeLocal flag and Only AdjustToUniversal flag is processed.

if ((styles & DateTimeStyles.AdjustToUniversal) != 0) { 
            return (AdjustTimeZoneToUniversal(ref result)); 
        } 
        return (AdjustTimeZoneToLocal(ref result, bTimeOnly)); 

On the other hand TryParseExact method is correctly implemented and it has all the required logic to handle DateTimeStyles.AssumeLocal flag. See how additional case is handled in this implementation.

            // 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 框架代码很有趣。如果您有兴趣,请按照 here 中的步骤操作.