Converting DateTime + TimeZone to UTC

早过忘川 提交于 2019-12-07 22:50:04

问题


How can I get universal time for a specified TimeZone, given a DateTime object? My application (a Timer) asks the user to specify a time and a timezone and I need to save the UTC based on the specified time+timezone values.

For example, user A specifies
DateTime: 07/06/2011 7:30 AM TimeZone: Eastern Standard Time (-5:00).

User B specifies:
DateTime: 07/06/2011 05:00 PM TimeZone: India Standard Time (+5:30).

I believe the UTC for both the above DateTime values will be the same and both of the above timers will occur at the same time. The problem is how do I get the UTC to save in the database? I am not able to get matching UTCs for the above datetime values.


回答1:


You can use DateTime in combination with TimeZoneInfo:

var utc = TimeZoneInfo.ConvertTimeToUtc(dateTimeAsEnteredByUser,
                                        timeZoneChosenByUser);

You need to make sure, that the Kind property of dateTimeAsEnteredByUser is set to DateTimeKind.Unspecified.

BTW:
The two times you specified are not the same. The first is 12:30 UTC and the second one is 11:30 UTC. Additionally, 17:00 PM doesn't exist, it's either 17:00 or 5:00 PM.




回答2:


Converting to Utc:

DateTime utcDateTime = TimeZoneInfo.ConvertTimeToUtc(dateTime, timeZone);


来源:https://stackoverflow.com/questions/6595706/converting-datetime-timezone-to-utc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!