wp8 c#中的时区转换

本文关键字:时区 转换 wp8 | 更新日期: 2023-09-27 18:05:27

我想知道没有办法将一个时区的日期和时间转换为另一个!!我有很多关于时区转换的例子,都是在非WP SDK上。令人惊讶的是TimeZoneInfo类的命名空间System WP SDK中没有FindSystemTimeZoneById()的方法。

如何在c#中将日期时间转换为特定的时区?除了WP SDK之外,都是在。net上转换时区的很好的例子。假设有这样一个场景,我有一个澳大利亚西部标准时间的时间,现在我需要将该时间转换为东部标准时间。通常我会这样做:
string timeZoneStringOne = "W. Australia Standard Time";
TimeZoneInfo timeZoneIDOne = TimeZoneInfo.FindSystemTimeZoneById(timeZoneStringOne);
string timeZoneStringTwo = "Eastern Standard Time";
TimeZoneInfo timeZoneIDTwo = TimeZoneInfo.FindSystemTimeZoneById(timeZoneStringTwo);
DateTime dt = new DateTime(2010, 02, 08, 05, 00, 00);
DateTimeOffset dtOffset1 = new DateTimeOffset(dt, timeZoneIDOne.GetUtcOffset(dt));
Console.WriteLine(dtOffset1);
DateTimeOffset dtOffset2 = TimeZoneInfo.ConvertTime(dtOffset1, timeZoneIDTwo);
Console.WriteLine(dtOffset2);
DateTimeOffset dtOffset3 = TimeZoneInfo.ConvertTime(dtOffset2, timeZoneIDOne);
Console.WriteLine(dtOffset3);
Console.ReadKey();
/*
  Output :
  2/8/2010 5:00:00 AM +08:00
  2/7/2010 4:00:00 PM -05:00
  2/8/2010 5:00:00 AM +08:00
*/

但是我怎么在windows phone 8上做呢??

wp8 c#中的时区转换

不幸的是,TimeZoneInfo对象在WP8和WinRT上是瘫痪的,因为没有FindSystemTimeZoneById,甚至没有Id属性。

恕我直言,最好的解决方案是使用野田时间。当作为可移植类库(PCL)编译时,它可以很好地运行在WP8上。PCL是最新NuGet包的默认版本,所以你应该可以简单地使用它。

但是,您将需要使用IANA时区而不是Microsoft的时区,因为BCL时区提供程序在便携式版本中不可用。

// Get the input value
LocalDateTime ldt1 = new LocalDateTime(2010, 2, 8, 5, 0, 0);
DateTimeZone tz1 = DateTimeZoneProviders.Tzdb["Australia/Perth"];
ZonedDateTime zdt1 = ldt1.InZoneLeniently(tz1);
// Convert to the target time zone
DateTimeZone tz2 = DateTimeZoneProviders.Tzdb["America/New_York"];
ZonedDateTime zdt2 = zdt1.WithZone(tz2);
// If you need a DateTimeOffset, you can get one easily
DateTimeOffset dto = zdt2.ToDateTimeOffset();

最近我得到了另一个不使用任何其他Lib的解决方案。就我而言,它解决了我的问题。在我的情况下,一个时区是固定的(例如我的时区是UTC -4并且需要将其转换为系统本地时间),所以我可以将其转换为UTC时间,然后将其转换为我系统的本地时区,在这种特殊情况下,wp sdk通过使用AddHours()方法DateTime

string GetLocalDateTime(DateTime targetDateTime)
{
    int fromTimezone = -3;
    int localTimezone;
    if (TimeZoneInfo.Local.BaseUtcOffset.Minutes != 0)
        localTimezone = Convert.ToInt16(TimeZoneInfo.Local.BaseUtcOffset.Hours.ToString() + (TimeZoneInfo.Local.BaseUtcOffset.Minutes / 60).ToString());
    else
        localTimezone = TimeZoneInfo.Local.BaseUtcOffset.Hours;
    DateTime Sdt = targetDateTime;
    DateTime UTCDateTime = targetDateTime.AddHours(-(fromTimezone));
    DateTime localDateTime = UTCDateTime.AddHours(+(localTimezone));
    return localDateTime.ToLongDateString() + " " + localDateTime.ToShortTimeString();
}