[英]Converting DateTime to UTC and back
也许听起来有些怪异,但我实际上知道此问题的解决方案。 我最初的解决方案不起作用,我实际上想知道为什么。 它是一个Asp.Net MVC应用程序。
这不起作用:
public static DateTime ConvertToUTC(String userTimeZone, DateTime date)
{
var result = TimeZoneInfo.ConvertTimeToUtc(date, TimeZoneInfo.FindSystemTimeZoneById(userTimeZone));
return result;
}
public static DateTime ConvertToUserTime(string userTimeZone, DateTime date)
{
var result = TimeZoneInfo.ConvertTimeFromUtc(date, TimeZoneInfo.FindSystemTimeZoneById(userTimeZone));
return result;
}
我无法将时间转换回原来的时间。
这确实有效:
public DateTime ConvertToUTC(String userTimeZone, DateTime date)
{
var result = TimeZoneInfo.ConvertTimeToUtc(result, TimeZoneInfo.FindSystemTimeZoneById(userTimeZone));
return result;
}
public DateTime ConvertToUserTime(string userTimeZone, DateTime date)
{
var userTimezoneInfo = TimeZoneInfo.FindSystemTimeZoneById(userTimeZone);
var result = date.Add(userTimezoneInfo.BaseUtcOffset);
return result;
}
有人有主意吗?
对于此问题,.NET 3.5中引入了特殊的DataType: DateTimeOffset,其功能与DateTime类似,但它还存储UTC偏移量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.