views:

50

answers:

2

Suppose I have a particular UTC time T. I would like a method that returns true if it is possible that at least one spot somewhere else on Earth has the same local date as T right now.

def still_same_date?(t)
  # true
  #   if it is the same day at some other place on Earth
  # false
  #   otherwise
end

For example, let's say T is today at 12:01 AM in my local time. Then clearly it's true, because anyplace east of me will also have today's date (it is later in the day at those spots).

But if T is yesterday at 4:00 PM in my local time, it is no longer obviously true that there is another place on Earth that still has that date.

And if T is January 1, 2000 at 6:58 PM in my local time, it is obviously false that there is another place on Earth with the same date.

How can I write still_same_date? so that it returns what I want?

+2  A: 

Okay, to clarify this, you actually have two pieces of information:

  • A UTC instant
  • A date

You want to see if at the given UTC instant, there are any time zones such that the date would be the given one. Note that your talk of "today" in the question doesn't give a unique value for the date (due to different time zones - my "today" may not be the same as yours), which is why I've explicitly couched it in terms of a function with two parameters.

Basically, you need to iterate. Pseudocode:

for each time zone tz
  localTime = tz.GetLocalTime(utc)
  if (localTime.GetDate() == targetDate)
    return true

return false

Now you can definitely optimize this by finding the largest and smallest time zone offsets which would give you a "true" result, and applying boundaries. I can't remember offhand what the largest and smallest offsets ever are, but I would safely guess that if you would need more than +15 or less than -15, you can return false immediately.

You can likewise cut down on the time zones you test, to only use those which are known to be at an extreme at some point in history.

Unless this is performance-critical though, I'd write the simple code and leave a TODO for optimization :)

Jon Skeet
+2  A: 

Basically, if DateTime.UtcNow is +/- 12 hours from your UTC date, you should return true... if I understood you correctly.

David Moye
@David: That's not always an "if and only if" though... IIRC there are places which can, at times, be +13:30 or something similar.
Jon Skeet
There are timezones that are in 30-minute increments yes, but there's nothing higher than +12 or lower than -12.
David Moye
@David: At any point of the year? I don't believe that's true. Trying to find a counterexample now...
Jon Skeet
@David: Found a counterexample. http://timeanddate.com/worldclock/city.html?n=274 "Standard time zone: UTC/GMT +14 hours"
Jon Skeet
You are correct. There are 4 time zones that violate the rule. Bah. Nobody lives there anyways ;) See http://en.wikipedia.org/wiki/List_of_time_zones for details.
David Moye