[英]Converting DateTime to UTC and back
Maybe it will sound a bit weird, but i actually know a solution for this problem. 也许听起来有些怪异,但我实际上知道此问题的解决方案。 My initial solution didn't work and i actually want to why.
我最初的解决方案不起作用,我实际上想知道为什么。 It is an Asp.Net MVC application.
它是一个Asp.Net MVC应用程序。
This didn't work: 这不起作用:
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;
}
I couldn't convert the time back to it's original time. 我无法将时间转换回原来的时间。
This did work: 这确实有效:
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;
}
Does anybody have an idea? 有人有主意吗?
对于此问题,.NET 3.5中引入了特殊的DataType: DateTimeOffset,其功能与DateTime类似,但它还存储UTC偏移量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.