Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?

Re: Comparing DateTime objects in different timezones

by haukex (Archbishop)
on Nov 01, 2017 at 10:50 UTC ( #1202508=note: print w/replies, xml ) Need Help??

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!

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1202508]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (6)
As of 2022-08-17 08:15 GMT
Find Nodes?
    Voting Booth?

    No recent polls found