ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

c# – .NET中的DateTime时区似乎是错误的?

2019-06-22 09:53:32  阅读:459  来源: 互联网

标签:c datetime net datetime-format


我一直在使用.NET MVC中的字符串解析DateTime,我发现了一些奇怪的行为.看看这个测试:

[Test]
public void DoesItWork()
{
    DateTime theTime = DateTime.Now;
    DateTime theUTCTime = theTime.ToUniversalTime();
    Assert.IsTrue(theTime==theUTCTime);         
}

我现在在英国,它的BST,所以我希望UTC时间比DateTime.Now的值晚一个小时.就是这样.但是当我在初始日期时间调用.ToUniversalTime()以及减去一个小时时,值的Kind属性也会更新 – 从Local到Utc.这也是我所期待的.

但是当我来比较这两个DateTime变量的值时,相等运算符不考虑不同的Kind值,只是报告它们是不同的值.对我而言,这似乎是错误的.

任何人都可以解释为什么它这样工作?

解决方法:

根据MSDNMSDN2,当您比较两个DateTime值时:

Remarks
To determine the relationship of the current instance to value, the CompareTo method compares the Ticks property of the current instance and value but ignores their Kind property. Before comparing DateTime objects, make sure that the objects represent times in the same time zone. You can do this by comparing the values of their Kind properties.

Remarks
The Equality operator determines whether two DateTime values are equal by comparing their number of ticks. Before comparing DateTime objects, make sure that the objects represent times in the same time zone. You can do this by comparing the values of their Kind property.

所以这是正确的.

链接到DateTime.Kind Property并再次发表评论:

The Kind property allows a DateTime value to clearly reflect either Coordinated Universal Time (UTC) or the local time. In contrast, the DateTimeOffset structure can unambiguously reflect any time in any time zone as a single point in time.

UPDATE

关于你的评论.恕我直言,这是预期的行为.因为通常,您不需要比较来自不同时区的两个DateTime.如果你需要这样做,你必须使用DateTimeOffset DateTimeOffset Structure,它是:

Remarks
The DateTimeOffset structure includes a DateTime value, together with an Offset property that defines the difference between the current DateTimeOffset instance’s date and time and Coordinated Universal Time (UTC). Because it exactly defines a date and time relative to UTC, the DateTimeOffset structure does not include a Kind member, as the DateTime structure does. It represents dates and times with values whose UTC ranges from 12:00:00 midnight, January 1, 0001 Anno Domini (Common Era), to 11:59:59 P.M., December 31, 9999 A.D. (C.E.).

标签:c,datetime,net,datetime-format
来源: https://codeday.me/bug/20190622/1262263.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有