2013-03-04 26 views
2

我有作为输入:如何将时间和奥尔森时区转换为另一个奥尔森时区的时间?

  1. 的时间(上午8:00)
  2. 的奥尔森时区(美国/纽约)

,我需要时间转换成另一个时区奥尔森( America/Los_Angeles)

什么是在.net或nodatime做这种转换的最佳方式。我基本上是在寻找这种方法在C#中的等价物:

var timeInDestinationTimeZone = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(CurrentSlot.Date, TimeZoneInfo.Local.Id, 
                      room.Location.TimeZone.TimeZoneName); 

但这种.NET方法上面只与Windows时区名称的工作(我有奥尔森名)

+0

[从奥尔森时区.NET的TimeZoneInfo]的可能重复(http://stackoverflow.com/questions/5996320/net -timezoneinfo -ofolson-time-zone) – 2013-03-04 04:40:13

+1

这不是重复的。另一个问题是要求映射到Windows时区。我不想这样做。我只是想转换时间,并保持olson格式的所有时区信息 – leora 2013-03-04 04:50:14

+0

你不能通过Windows时区去做那里的转换吗? – 2013-03-04 05:00:08

回答

4

观察:

var tzdb = DateTimeZoneProviders.Tzdb; 

var zone1 = tzdb["America/New_York"]; 
var ldt1 = new LocalDateTime(2013, 3, 4, 8, 0); // March 4th, 2013 - 8:00 AM 
var zdt1 = zone1.AtLeniently(ldt1); 

var zone2 = tzdb["America/Los_Angeles"]; 
var zdt2 = zdt1.ToInstant().InZone(zone2); 
var ldt2 = zdt2.LocalDateTime; 

请注意拨打AtLeniently--这是因为您没有足够的信息来确定您正在谈论的时刻。例如,如果您在DST回落转换当天的凌晨1:30说话,则在转换之前或之后您不知道您是在说什么。 AtLeniently会在之后作出你的意思是。如果你不想要这种行为,你必须提供一个偏移量,以便你知道你正在谈论的当地时间。

实际转换正在ToInstant它让你在谈论UTC片刻,然后InZone这是将其应用于目标区进行。

+0

看到我的答案为最后一点的另一种选择 - 但这很好。 – 2013-03-05 04:35:59

3

马特的(完美的)答案的第二部分的替代:

// All of this part as before... 
var tzdb = DateTimeZoneProviders.Tzdb;  
var zone1 = tzdb["America/New_York"]; 
var ldt1 = new LocalDateTime(2013, 3, 4, 8, 0); // March 4th, 2013 - 8:00 AM 
var zdt1 = zone1.AtLeniently(ldt1); 

var zone2 = tzdb["America/Los_Angeles"]; 

// This is just slightly simpler - using WithZone, which automatically retains 
// the calendar of the existing ZonedDateTime, and avoids having to convert 
// to Instant manually 
var zdt2 = zdt1.WithZone(zone2); 
var ldt2 = zdt2.LocalDateTime; 
+0

啊,谢谢。我忘记了'WithZone'。:) – 2013-03-05 04:56:09

+0

@Jon Skeet - 我必须给马特接受,因为我用它,它运作良好(你有很多被接受的答案:))。昨天花了很多时间阅读了NodaTime文档,并学会了吨...感谢花时间把这个libarary放在一起。 。 – leora 2013-03-05 05:50:03

+0

@leora:我很高兴它为你而来 - 请发送邮件列表反馈我们可以改进文档的位置。 – 2013-03-05 12:42:33

相关问题