我正在尝试将转换时间转换为用户的时区,但我没有 Windows 时区字符串,例如“太平洋标准时间”。我所拥有的只是一个字符串偏移量,例如“-07:00”。看来我需要创建一个时间跨度。是手动解析该字符串的唯一方法吗?似乎应该有一种方法使用字符串偏移量来转换时间,但也许我错过了一些东西。
我有这个,但它需要时区。我正在尝试修改它以使用偏移量,但您可以看到为转换创建的时间跨度,并且我需要获取时间跨度的偏移量。
static void Main(string[] args)
{
var currentTimeInPacificTime = ConvertUtcTimeToTimeZone(DateTime.UtcNow, "Pacific Standard Time");
//TimeSpan ts = new TimeSpan("-07:00");
Console.ReadKey();
}
static DateTimeOffset ConvertUtcTimeToTimeZone(DateTime dateTime, string toTimeZoneDesc)
{
if (dateTime.Kind != DateTimeKind.Utc) throw new Exception("dateTime needs to have Kind property set to Utc");
TimeSpan toUtcOffset = TimeZoneInfo.FindSystemTimeZoneById(toTimeZoneDesc).GetUtcOffset(dateTime);
var convertedTime = DateTime.SpecifyKind(dateTime.Add(toUtcOffset), DateTimeKind.Unspecified);
return new DateTimeOffset(convertedTime, toUtcOffset);
}
你可以只使用TimeSpan.Parse http://msdn.microsoft.com/en-us/library/se73z7b9.aspx method:
TimeSpan ts = TimeSpan.Parse("-07:00");
Console.WriteLine(ts); // -07:00:00
请小心去掉前导“+”,因为 TimeSpan.Parse 在这里会失败。 “+01:00”不正确,但“01:00”有效。
或者,如果您想更安全一点,请尝试TimeSpan.TryParse http://msdn.microsoft.com/en-us/library/3z48198e.aspx method:
TimeSpan ts;
if (TimeSpan.TryParse("-07:00", out ts))
Console.WriteLine(ts); // -07:00:00
但当然,如果您只想将 UTC 日期/时间转换为本地日期/时间,您可以这样做:
DateTime localDateTime = utcDateTime.ToLocalTime();
或者将其转换为任何时区:
TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById(toTimeZoneDesc);
DateTime localDateTime = TimeZoneInfo.ConvertTime(utcDateTime, tzi);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)