2

When converting times between time zones. I found the follow code works. However I am not sure how programmatically what to put as my offset for the constructor for the ZonedDateTime. I had a choice of one of the offsets on zoneChicago, which is just two, because its either with our without daylight savings, but how do I know which one I use, and for timezones that have more then just two, what is the best way to populate that offset?

Thanks,

Jim

var zoneLA      = c.GetZoneOrNull("America/Los_Angeles");
var zoneChicago = c.GetZoneOrNull("America/Chicago");

var zdtChicago = new ZonedDateTime( LocalDateTime.FromDateTime(DateTime.Now)
                                  , zoneChicago
                                  , zoneChicago.MaxOffset);

var zdtLA = zdtChicago.WithZone(zoneLA);
Noctis
  • 11,507
  • 3
  • 43
  • 82
Jim
  • 61
  • 6
  • Okay, tried this, not sure if this is correct: `var zoneLA = c.GetZoneOrNull("America/Los_Angeles");` `var zoneChicago = c.GetZoneOrNull("America/Chicago");` `var now = DateTime.Now;` `var iNow = Instant.FromDateTimeUtc(now.ToUniversalTime());` `var zdtChicago = new ZonedDateTime(LocalDateTime.FromDateTime(now), zoneChicago, zoneChicago.GetZoneInterval(iNow).WallOffset);` `var zdtLA = zdtChicago.WithZone(zoneLA);` – Jim May 15 '13 at 21:50
  • Will have a look at this when I get time - soon, I promise! It's probably worth moving your comment into the question for the sake of readability though. – Jon Skeet May 16 '13 at 10:03

1 Answers1

3

If you're interested in the current time, you can make this much simpler - and indeed more testable. Make your code take an IClock as a "service for providing the current instant in time". For the concrete implementation, use SystemClock.Instance in production, but FakeClock for testing.

IClock has a single member: Now. That returns the current Instant in time, which isn't tied to a time zone or even a calendar system.

With an Instant and a time zone, you can easily get to a ZonedDateTime:

Instant now = clock.Now;
var zone = DateTimeZoneProviders.Tzdb["America/Los_Angeles"];
ZonedDateTime = now.InZone(zone);

It will work out what the local date/time and offset is. You don't need to do anything clever :)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194