C#从固定时区转换DateTime
我正在从外部API日期阅读:
2022-05-13 07:05:00
2022-05-13 13:00:00 ...
这些日期是在CET时间固定的。我想将它们转换为UTC格式,例如“ yyyy-mm-ddthh:mm:sszzz”,这样我就可以看到UTC偏移+02:00。
问题在于我没有找到一种方法来指定我的日期位于CET时区。诸如转换时间之类的函数,转换timetoutc不起作用。
我的代码是:
var time = new DateTime(2022,5,26,8,15,00, DateTimeKind.Unspecified); // 2022-05-26 8:15:00 CET
TimeZoneInfo tz = TimeZoneInfo.FindSystemTimeZoneById("Central European Standard Time");
DateTime cet = TimeZoneInfo.ConvertTime(time, tz); // non sense, as no timezone info in time...
var str = cet.ToString("yyyy-MM-ddTHH:mm:sszzz");
如何解决这个问题?
I'm reading from external API dates like this:
2022-05-13 07:05:00
2022-05-13 13:00:00
...
These dates are fixed in CET time. I want to convert them into UTC format like "yyyy-MM-ddTHH:mm:sszzz" so I can see UTC offset +02:00.
The problem is that I didn't find a way how to specify that my date is in CET timezone. Functions like ConvertTime, ConvertTimeToUtc doesn't work.
My code is:
var time = new DateTime(2022,5,26,8,15,00, DateTimeKind.Unspecified); // 2022-05-26 8:15:00 CET
TimeZoneInfo tz = TimeZoneInfo.FindSystemTimeZoneById("Central European Standard Time");
DateTime cet = TimeZoneInfo.ConvertTime(time, tz); // non sense, as no timezone info in time...
var str = cet.ToString("yyyy-MM-ddTHH:mm:sszzz");
How to resolve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
有一种更清洁的方法:
输出是一致和正确的,总是尊重日光节省时间段:
边缘案例:
2022-03-27 02:30:00 CET
。在这种情况下,根据和例外:
2022-10 -30 02:30:00 CET
在逻辑上可以转化为 00:30:00 UTC或 01:30:00 UTC 。在这种情况下,根据标准时间(冬季)时间:
There is a cleaner way of doing it:
The output is consistent and correct, always respecting daylight saving time period:
Edge cases:
2022-03-27 02:30:00 CET
.In this case according to the documentation and exception is thrown:
2022-10-30 02:30:00 CET
could logically translate to either of 00:30:00 UTC or 01:30:00 UTC.In this case according to the documentation standard (winter) time is assumed:
您可以使用以下几个小时手动设置:
然后可以格式化日期时间对象,而不必担心时区。
编辑:添加日光节省。
首先,您必须检查您是否在节省日光有效的时候。
要进行此操作,请首先获取DateTime,然后检查是否在日光节省期间。
日光节省在3月的最后一个星期日生效,并在10月的最后一个星期日被取消
You can manually set the hours back using:
And then you can format the date time object without worrying about the time zones.
edit: adding daylight saving.
First you have to check whether you are in the time where daylight saving is in effect or not.
To do this first get the datetime, then check if it is in the daylight saving period.
Daylight saving goes into effect at the last sunday of march and is cancelled at the last sunday of october