用户在单独的文本框中输入日期和时间。然后我将日期和时间合并到一个日期时间。我需要将此日期时间转换为UTC以将其保存在数据库中。我将用户的时区ID保存在数据库中(他们在注册时选择它)。首先,我试过如下:将用户输入的UTC转换为UTC
string userTimeZoneID = "sometimezone"; // Retrieved from database
TimeZoneInfo userTimeZone = TimeZoneInfo.FindSystemTimeZoneById(userTimeZoneID);
DateTime dateOnly = someDate;
DateTime timeOnly = someTime;
DateTime combinedDateTime = dateOnly.Add(timeOnly.TimeOfDay);
DateTime convertedTime = TimeZoneInfo.ConvertTimeToUtc(combinedDateTime, userTimeZone);
这导致一个例外:
The conversion could not be completed because the supplied DateTime did not have the Kind property set correctly. For example, when the Kind property is DateTimeKind.Local, the source time zone must be TimeZoneInfo.Local
然后我尝试设置一种属性,像这样:
DateTime.SpecifyKind(combinedDateTime, DateTimeKind.Local);
这并没有工作,所以我试过了:
DateTime.SpecifyKind(combinedDateTime, DateTimeKind.Unspecified);
这也没有工作。任何人都可以解释我需要做什么?我甚至会以正确的方式去解决这个问题吗?我应该使用DateTimeOffset吗?
[转换本地时间UTC在.NET框架3.0]可能重复(http://stackoverflow.com/questions/4668921/convert-local-time -to-utc-in-net-framework-3-0) – Shai 2012-08-12 06:58:10
@Shai:显然不是重复的,因为这个问题有:“我必须在.NET Framework 3.0中使用,所以不能使用TimeZoneInfo对象。” – 2012-08-12 07:02:37
@JonSkeet Ahhh没有看到,可能会给OP一个主角.. – Shai 2012-08-12 07:19:00