[Discussed TimeDiffs John Goerzen **20071024050805] { hunk ./en/ch20-systems.xml 246 + asdf + + hunk ./en/ch20-systems.xml 251 + + TimeDiff for ClockTime + + Because it can be difficult to manage differences between + &ClockTime; values in a human-friendly way, the + System.Time module includes a &TimeDiff; type. + &TimeDiff; can be used, where convenient, to handle these + differences. It is defined like this: + + +data TimeDiff = TimeDiff + {tdYear :: Int, + tdMonth :: Int, + tdDay :: Int, + tdHour :: Int, + tdMin :: Int, + tdSec :: Int, + tdPicosec :: Integer} + + + Functions such as diffClockTimes and + addToClockTime take a &ClockTime; and a + &TimeDiff; and handle the calculations internally by converting to + a &CalendarTime; in UTC, applying the differences, and converting + back to a &ClockTime;. + + + Let's see how it works: + + &timediff.ghci:all; + + We started by generating a &ClockTime; representing midnight + February 5, 2008 in UTC. Note that, unless your timezone is the + same as UTC, when this time is printed out on the display, it may + show up as the evening of February 4 because it is formatted for + your local timezone. + + + Next, we add one month to to it by calling + addToClockTime. 2008 is a leap year, but the + system handled that properly and we get a result that has the same + date and time in March. By using toUTCTime, we + can see the effect on this in the original UTC timezone. + + + For a second experiment, we set up a time representing midnight + on January 30, 2009 in UTC. 2009 is not a leap year, so we might + wonder what will happen when trying to add one month to it. We can + see that, since neither February 29 or 30 exist in 2009, we wind up + with March 2. + + + Finally, we can see how diffClockTimes turns two + &ClockTime; values into a &TimeDiff;, though only the seconds and + picoseconds are filled in. The + normalizeTimeDiff function takes such a + &TimeDiff; and reformats it as a human might expect to see it. + + + addfile ./examples/ch20/timediff.ghci hunk ./examples/ch20/timediff.ghci 1 +--# all +:m System.Time +let feb5 = toClockTime $ CalendarTime 2008 February 5 0 0 0 0 Sunday 0 "UTC" 0 False +feb5 +addToClockTime (TimeDiff 0 1 0 0 0 0 0) feb5 +toUTCTime $ addToClockTime (TimeDiff 0 1 0 0 0 0 0) feb5 +let jan30 = toClockTime $ CalendarTime 2009 January 30 0 0 0 0 Sunday 0 "UTC" 0 False +jan30 +addToClockTime (TimeDiff 0 1 0 0 0 0 0) jan30 +toUTCTime $ addToClockTime (TimeDiff 0 1 0 0 0 0 0) jan30 +diffClockTimes jan30 feb5 +normalizeTimeDiff $ diffClockTimes jan30 feb5 }