从字符串创建 DateTime 而不应用时区或夏令时
如何从已针对 UTC 调整的字符串创建 DateTime 变量?我在设置为 BST (GMT+1) 的计算机上运行此程序。如果我运行以下代码行:
DateTime clientsideProfileSyncStamp = Convert.ToDateTime("20-May-2011 15:20:00");
然后在针对保存 (UTC) 值的数据库的测试中使用该值,那么看起来 Convert.ToDateTime() 实际上给我的 UTC 值是 14:20。我不希望它进行转换 - 我只是希望它接受我的 DateTime 字符串已经采用 UTC 格式。
谢谢。
How do I create a DateTime var from a string which is already adjusted for UTC? I am running this on a machine set to BST (GMT+1). If I run the following line of code:
DateTime clientsideProfileSyncStamp = Convert.ToDateTime("20-May-2011 15:20:00");
and then use the value in a test against a database holding (UTC) values then it would appear that the Convert.ToDateTime() is actually giving me a UTC value of 14:20. I don't want it to do the conversion - I just want it to accept that my DateTime string is already in UTC.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
解析字符串,并指定当字符串中没有指定时区时应采用 UTC 时间:
Parse the string, and specify that it should assume UTC time when there is no time zone specified in the string:
使用
广告不足的
DateTimeOffset
type 表示时间点,无论时区差异如何,因此应优先使用需要“时间戳”的 DateTime。Use
The under-advertised
DateTimeOffset
type represents a point in time regardless of timezone differences, and as such should be used in preference to DateTime where a 'timestamp' is required.@Guffa 的答案非常好,但我想添加一个额外的答案。
如果您的日期时间字符串看起来像这样“2017-11-27T05:30:00.000Z”,那么 AssumeUniversal 不起作用。
试试这个:
AssumeUniversal 和 AdjustToUniversal 之间有细微的差别。请阅读此处:AssumeUniversal 和 AdjustToUniversal 之间的区别
@Guffa's answer is very good but i will like to add an additional answer.
If your datetime string is looking like this "2017-11-27T05:30:00.000Z" then AssumeUniversal is not working.
Try this :
There is a slight difference between AssumeUniversal and AdjustToUniversal. Read here : Difference between AssumeUniversal and AdjustToUniversal
将
Z
添加到日期时间字符串:Add a
Z
to the DateTime string:不要忘记
TryParse
变体,它允许您处理解析错误而不发生异常。此外,如果您不使用
ParseExact
或TryParseExact
,它也会假设输出Kind
是Local
,因此您可能还想使用ToUniversalTime()
Don't forget the
TryParse
variant which allows you to handle a parse error without an exceptionAlso if you are not using
ParseExact
orTryParseExact
it will assume the outputKind
isLocal
so you may also want to useToUniversalTime()
DateTime.Parse()
或DateTime.TryParse()
DateTime.Parse()
orDateTime.TryParse()
要创建独立于区域性的 DateTime,请使用:
然后日期始终与字符串中定义的完全相同。
To create culture independent DateTime use:
Then the date stays always exactly as defined in string.