如何解决为什么DateTime不能转换为指定的TimeZone?
我有一个mysql数据库,用户可以向其中添加约会记录,并且我希望具有可以根据用户计算机的时区自动更改约会的DateTime值的功能。由于某种原因,我无法使它正常工作。
我已经尝试了现有的解决方案,但也许我遗漏了一些东西?任何时候将日期信息发送到数据库,我都会将时间转换为UTC:
private void UpdateAppointment()
{
using (ent = new ScheduleEntities())
{
var currentAppointment = ent.appointments.Attach(AppointmentIndex);
currentAppointment.start = start_TimePicker.Value.ToUniversalTime();
currentAppointment.end = end_TimePicker.Value.ToUniversalTime();
ent.SaveChanges();
}
}
然后在将记录添加到列表之前,我将转换为本地时区:
private void ChangeTimeZone()
{
Debug.WriteLine($"{TimeZone.CurrentTimeZone.StandardName}");
foreach (var item in userAppointments)
{
Debug.WriteLine($"before: {item.start} - {item.end}");
item.start = DateTime.SpecifyKind(item.start,DateTimeKind.Local);
item.end = DateTime.SpecifyKind(item.start,DateTimeKind.Local);
item.start = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(item.start,TimeZone.CurrentTimeZone.StandardName);
item.end = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(item.end,TimeZone.CurrentTimeZone.StandardName);
Debug.WriteLine($"after: {item.start} - {item.end}");
}
}
private void PopulateAppointmentGrid()
{
if (all_Radio.Checked)
{
ChangeTimeZone();
var allQuery = ent.appointments.Where(ap => ap.userId == ActiveUser.userId);
ForEachListItem(allQuery,ap => userAppointments.Add(ap));
}
}
Debug.WriteLine结果:
- TimeZone(我从东部手动设置为中部,可以识别更改)
- 之前:上午8点
- 之后:上午8点
完整代码可在此处找到:
https://github.com/AustinSB/SchedulingApplication
解决方法
DateTime
对象从MySQL返回为DateTimeKind.Unspecified
。执行此代码时,它会强制将其视为本地时间,但不会更改实际时间值:
item.start = DateTime.SpecifyKind(item.start,DateTimeKind.Local);
item.end = DateTime.SpecifyKind(item.start,DateTimeKind.Local);
这似乎不正确,因为您保存了UTC值:currentAppointment.start = start_TimePicker.Value.ToUniversalTime();
您的时区转换很可能什么也不做,因为它们已经在当地时间了。
您可以尝试DateTime.SpecifyKind(item.start,DateTimeKind.Universal);
,但是如果您使用多个时区,则可能会遇到另一组错误。
请考虑存储完整的DateTimeOffset
值,如本文所述:https://mysqlconnector.net/troubleshooting/datetime-storage/。
几件事:
-
您正在使用
.ToUniversalTime()
从本地时间正确转换为UTC。之所以有效,是因为当Kind
为Unspecified
时,它将被视为本地。因此,您正在将UTC值保存到数据库中。 -
您错误地断言从数据库中检索到的值是本地时间。相反,断言它们是
SpecifyKind
的UTC,然后使用ToLocalTime
转换为本地时间。此外,要使该操作幂等,建议在进行任何转换之前检查
Unspecified
类型。如果您多次调用方法,这将防止双重转换。if (item.start.Kind == DateTimeKind.Unspecified) { item.start = DateTime.SpecifyKind(item.start,DateTimeKind.Utc).ToLocalTime(); } if (item.end.Kind == DateTimeKind.Unspecified) { item.end = DateTime.SpecifyKind(item.end,DateTimeKind.Utc).ToLocalTime(); }
-
由于您仅在本地时间和UTC之间工作,因此不需要获取系统的当前时区或时区标识符,也不需要使用
TimeZone
或TimeZoneInfo
类。 (此建议仅适用,因为这是Windows Forms桌面应用程序。不适用于Web应用程序,因为服务器的本地时区控制着本地时间。) -
完全不使用
TimeZone
类。曾经原因很多,并说明了in the documentation。具体来说,在这种情况下,请注意TimeZone.CurrentTimeZone.StandardName
返回一个本地化的字符串,该字符串将根据语言环境而变化,并且并不总是与ID对齐-即使是英文也是如此。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。