Question

I am trying to program a world clock using Nodatime, and I have searched the web for samples on how to use the library and I have read the documentation, and it says that the class Instant is simply a number of "ticks" since some arbitrary epoch the Unix epoch, which corresponds to midnight on January 1st 1970 UTC. Well, I empirically guessed that if I used as an Instant a GMT value, then I could calculate with it the time values for each time zone (creating the world clock), and it worked. The problem that I have, is that I don't know a simple way to calculate the GMT time (or GMT instant) from the local time, my time zone is "America/Mexico_City", so my question is, is there a shortcut already defined in Nodatime to get the GMT time from a local time, or in the other hand, is there a simple way to implement the "Instant GetInstantGMT()" function (the function has to take in count the day light saving time issues)?

Was it helpful?

Solution

If you are just looking for the "current" instant, such represents now, then use:

Instant now = SystemClock.Instance.Now;

Calling it a "GMT instant" is redundant, since the Instant type is representing a universal moment in time without regard to time zone. It is (mostly) equivalent to UTC - which is essentially the same as GMT. In other words, you couldn't create an Instant that wasn't GMT.

Another way to think about an Instant is as if it were a DateTime whose .Kind property was permanently fixed to DateTimeKind.Utc and could not represent anything else.

Also, depending on exactly how your application is architected, you may find it useful to use the IClock interface instead:

IClock clock = SystemClock.Instance;
Instant now = clock.Now;

This would allow you to replace the system clock with a fake clock during unit testing.

Regarding how to go from a specific local time to an Instant, you would do something like this:

LocalDateTime ldt = new LocalDateTime(2013, 1, 1, 0, 0, 0);
DateTimeZone tz = DateTimeZoneProviders.Tzdb["America/Mexico_City"];
ZonedDateTime zdt = ldt.InZoneLeniently(tz);
Instant instant = zdt.ToInstant();

Note that I used InZoneLeniently in the conversion. This makes certain assumptions about how to translate from a local time that might be invalid or ambiguous due to daylight saving time. This might be acceptable, or you might instead prefer to use InZoneStrictly which will throw exceptions, or InZone which allows you to pass a resolver function so you can provide your own logic.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top