http://qs321.pair.com?node_id=1202508


in reply to Comparing DateTime objects in different timezones

I specifically set the timezone of the two dates to Australia/Sydney and America/Los_Angeles.

Be careful with this, since using set_time_zone may actually change the time value. If you have parsed times that include time zone information, then you do not need to use set_time_zone unless you specifically want to represent the time in another zone, but this is not necessary for comparisons! Only if your time did not include time zone information and it is in the special "floating" zone should you use set_time_zone, because as per the DateTime docs, comparisons are best between objects in a specific time zone (even if it's just UTC). See also my post here.

Then I get the UTC offset of the two dates, to compare

It sounds like you might be over-thinking the solution - DateTime allows for comparison of objects even if they are in different time zones. See its docs: subtract_datetime_absolute "is the only way to accurately measure the absolute amount of time between two datetimes, since units larger than a second do not represent a fixed number of seconds." For example (from here):

my $diff_sec = $dt2->subtract_datetime_absolute($dt1)     ->in_units('seconds');

So your steps should be:

  1. Parse your strings into DateTime objects (e.g. DateTime::Format::Strptime)
  2. For debugging, print out your objects including TZ info (e.g.  $dt->strftime('%Y-%m-%d %H:%M:%S.%3N %Z (%z)'))
  3. If and only if any of the objects are in the "floating" zone, set their time zone.
  4. Use subtract_datetime_absolute to compare them, as shown above.

Since the DateTime family are my favorite modules for date/time processing, I've written about them a lot, you should be able to find some good snippets among my posts. Update: In fact, this post should give you everything you need!