转换日期时间+时区为UTC [英] Converting DateTime + TimeZone to UTC

查看:189
本文介绍了转换日期时间+时区为UTC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎样才能在指定的TimeZone世界时间,给定一个日期对象?我的应用程序(如定时器)要求用户指定的时间和时区,我需要根据保存在指定时间+时区值UTC。

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.

例如,用户A指定
日期时间:07/06/2011上午7:30时区:东部标准时间(-5:00)。

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

用户B规定:
日期时间:07/06/2011 17:00时区:印度标准时间(+5:30)。

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

相信与UTC为上述两个日期时间值将是相同的,并都在上述定时器将发生在同一时间。问题是我怎么得到UTC保存在数据库中?我不能够获得上述日期时间值匹配UTCS。

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.

推荐答案

您可以使用的DateTime 联合的TimeZoneInfo

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

您需要确保,即 dateTimeAsEnteredByUser 属性设置为 DateTimeKind.Unspecified

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

BTW:
你们两个指定的时间是不一样的。第一12:30 UTC与第二个11:30 UTC。此外,下午17:00不存在,它要么17:00或下午5:00。

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.

这篇关于转换日期时间+时区为UTC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆