【问题标题】:How to convert a time and olson timezone to the time in another olson timezone?如何将时间和 olson 时区转换为另一个 olson 时区的时间?
【发布时间】:2013-02-18 03:01:20
【问题描述】:

我有一个输入:

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

我需要将时间转换为另一个奥尔森时区(美国/洛杉矶)

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

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

但上面的这个 .Net 方法仅适用于 Windows 时区名称(我有 Olson 名称)

【问题讨论】:

  • 这不是重复的。另一个问题是要求映射到 Windows 时区。我不想那样做。我只想转换时间并以 olson 格式保存所有时区信息
  • 你不能通过 Windows 时区并在那里进行转换吗?
  • 是的,但是考虑到映射之间的所有问题,这会导致额外的复杂性和保真度损失。这正是我问这个问题的原因,因为我不想转换为 Windows 时间
  • 我在我的问题中列出了 nodatime。 .这是我的问题:)

标签: c# datetime nodatime


【解决方案1】:

马特(非常好)答案的第二部分的替代方案:

// 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;

【讨论】:

  • @Jon Skeet - 在我使用它时我不得不接受 Matt 并且它运行良好(而且你有很多接受的答案:))。昨天花了很多时间阅读 NodaTime 文档并学到了很多东西 ..感谢您花时间将这个库放在一起。 .
  • @leora:很高兴它为您服务 - 请向邮件列表发送有关我们可以改进文档的任何反馈。
【解决方案2】:

观察:

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 将其应用于目标区域。

【讨论】:

  • 查看我的答案以获得最后一点的另一个选项 - 但这很好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-05-06
  • 1970-01-01
  • 2015-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多