83c2867552ff50b39d1ef5544f7c30de7fb6d5ce
[ghc-hetmet.git] / ghc / lib / std / Time.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1995-97
3 %
4 \section[Time]{Haskell 1.4 Time of Day Library}
5
6 The {\em Time} library provides standard functionality for
7 clock times, including timezone information (i.e, the functionality of
8 "time.h",  adapted to the Haskell environment), It follows RFC 1129 in
9 its use of Coordinated Universal Time (UTC).
10
11 \begin{code}
12 {-# OPTIONS -#include "cbits/timezone.h" -#include "cbits/stgio.h"  #-}
13 module Time 
14        (
15         Month(..),
16         Day(..),
17
18         ClockTime(..), -- non-standard, lib. report gives this as abstract
19         getClockTime, 
20
21         TimeDiff(TimeDiff),
22         diffClockTimes,
23         addToClockTime,
24         timeDiffToString, -- non-standard
25         formatTimeDiff,   -- non-standard
26
27         CalendarTime(CalendarTime),
28         toCalendarTime, 
29         toUTCTime, 
30         toClockTime,
31         calendarTimeToString, 
32         formatCalendarTime
33
34        ) where
35
36 import PrelBase
37 import PrelIOBase
38 import PrelArr
39 import PrelST
40 import PrelAddr
41 import PrelPack         ( unpackCString )
42
43 import Ix
44 import Char             ( intToDigit )
45 import Locale
46
47 \end{code}
48
49 One way to partition and give name to chunks of a year and a week:
50
51 \begin{code}
52 data Month
53  = January   | February | March    | April
54  | May       | June     | July     | August
55  | September | October  | November | December
56  deriving (Eq, Ord, Enum, Bounded, Ix, Read, Show)
57
58 data Day 
59  = Sunday  | Monday | Tuesday | Wednesday
60  | Thursday | Friday | Saturday
61  deriving (Eq, Ord, Enum, Bounded, Ix, Read, Show)
62
63 \end{code}
64
65 @ClockTime@ is an abstract type, used for the internal clock time.
66 Clock times may be compared, converted to strings, or converted to an
67 external calendar time @CalendarTime@.
68
69 \begin{code}
70 data ClockTime = TOD Integer Integer deriving (Eq, Ord)
71 \end{code}
72
73 When a @ClockTime@ is shown, it is converted to a string of the form
74 @"Mon Nov 28 21:45:41 GMT 1994"@.
75
76 For now, we are restricted to roughly:
77 Fri Dec 13 20:45:52 1901 through Tue Jan 19 03:14:07 2038, because
78 we use the C library routines based on 32 bit integers.
79
80 \begin{code}
81 instance Show ClockTime where
82     showsPrec p (TOD sec@(J# a# s# d#) nsec) = 
83       showString $ unsafePerformIO $ do
84             buf <- allocChars 32
85             str <- _ccall_ showTime (I# s#) d# buf
86             return (unpackCString str)
87
88     showList = showList__ (showsPrec 0)
89 \end{code}
90
91
92 @CalendarTime@ is a user-readable and manipulable
93 representation of the internal $ClockTime$ type.  The
94 numeric fields have the following ranges.
95
96 \begin{verbatim}
97 Value         Range             Comments
98 -----         -----             --------
99
100 year    -maxInt .. maxInt       [Pre-Gregorian dates are inaccurate]
101 mon           0 .. 11           [Jan = 0, Dec = 11]
102 day           1 .. 31
103 hour          0 .. 23
104 min           0 .. 59
105 sec           0 .. 61           [Allows for two leap seconds]
106 picosec       0 .. (10^12)-1    [This could be over-precise?]
107 wday          0 .. 6            [Sunday = 0, Saturday = 6]
108 yday          0 .. 365          [364 in non-Leap years]
109 tz       -43200 .. 43200        [Variation from UTC in seconds]
110 \end{verbatim}
111
112 The {\em tzname} field is the name of the time zone.  The {\em isdst}
113 field indicates whether Daylight Savings Time would be in effect.
114
115 \begin{code}
116 data CalendarTime 
117  = CalendarTime  {
118      ctYear    :: Int,
119      ctMonth   :: Int,
120      ctDay     :: Int,
121      ctHour    :: Int,
122      ctMin     :: Int,
123      ctSec     :: Int,
124      ctPicosec :: Integer,
125      ctWDay    :: Day,
126      ctYDay    :: Int,
127      ctTZName  :: String,
128      ctTZ      :: Int,
129      ctIsDST   :: Bool
130  }
131  deriving (Eq,Ord,Read,Show)
132
133 \end{code}
134
135 The @TimeDiff@ type records the difference between two clock times in
136 a user-readable way.
137
138 \begin{code}
139 data TimeDiff
140  = TimeDiff {
141      tdYear    :: Int,
142      tdMonth   :: Int,
143      tdDay     :: Int,
144      tdHour    :: Int,
145      tdMin     :: Int,
146      tdSec     :: Int,
147      tdPicosec :: Integer -- not standard
148    }
149    deriving (Eq,Ord,Read,Show)
150 \end{code}
151
152 @getClockTime@ returns the current time in its internal representation.
153
154 \begin{code}
155 getClockTime :: IO ClockTime
156 getClockTime = do
157     i1 <- malloc1
158     i2 <- malloc1
159     rc <- _ccall_ getClockTime i1 i2
160     if rc == 0 
161         then do
162             sec  <- cvtUnsigned i1
163             nsec <- cvtUnsigned i2
164             return (TOD sec (nsec * 1000))
165         else
166             constructErrorAndFail "getClockTime"
167   where
168     malloc1 = IO $ \ s# ->
169         case newIntArray# 1# s# of 
170           StateAndMutableByteArray# s2# barr# -> 
171                 IOok s2# (MutableByteArray bottom barr#)
172
173     --  The C routine fills in an unsigned word.  We don't have 
174     --  `unsigned2Integer#,' so we freeze the data bits and use them 
175     --  for an MP_INT structure.  Note that zero is still handled specially,
176     --  although (J# 1# 1# (ptr to 0#)) is probably acceptable to gmp.
177
178     cvtUnsigned (MutableByteArray _ arr#) = IO $ \ s# ->
179         case readIntArray# arr# 0# s# of 
180           StateAndInt# s2# r# ->
181             if r# ==# 0# 
182                 then IOok s2# 0
183                 else case unsafeFreezeByteArray# arr# s2# of
184                         StateAndByteArray# s3# frozen# -> 
185                                 IOok s3# (J# 1# 1# frozen#)
186
187 \end{code}
188
189 @addToClockTime@ {\em d} {\em t} adds a time difference {\em d} and a
190 clock time {\em t} to yield a new clock time.  The difference {\em d}
191 may be either positive or negative.  @[diffClockTimes@ {\em t1} {\em
192 t2} returns the difference between two clock times {\em t1} and {\em
193 t2} as a @TimeDiff@.
194
195
196 \begin{code}
197 addToClockTime  :: TimeDiff  -> ClockTime -> ClockTime
198 addToClockTime (TimeDiff year mon day hour min sec psec) 
199                (TOD c_sec c_psec) = unsafePerformIO $ do
200     res <- allocWords (``sizeof(time_t)'')
201     ptr <- _ccall_ toClockSec year mon day hour min sec 0 res 
202     let (A# ptr#) = ptr
203     if ptr /= nullAddr
204      then let
205             diff_sec  = (int2Integer# (indexIntOffAddr# ptr# 0#))
206             diff_psec = psec
207           in
208           return (TOD (c_sec + diff_sec) (c_psec + diff_psec))
209      else
210           error "Time.addToClockTime: can't perform conversion of TimeDiff"
211
212
213 diffClockTimes  :: ClockTime -> ClockTime -> TimeDiff
214 diffClockTimes tod_a tod_b =
215   let
216    CalendarTime year_a mon_a day_a hour_a min_a sec_a psec_a _ _ _ _ _ = toUTCTime tod_a
217    CalendarTime year_b mon_b day_b hour_b min_b sec_b psec_b _ _ _ _ _ = toUTCTime tod_b
218   in
219   TimeDiff (year_a - year_b) 
220            (mon_a  - mon_b) 
221            (day_a  - day_b)
222            (hour_a - hour_b)
223            (min_a  - min_b)
224            (sec_a  - sec_b)
225            (psec_a - psec_b)
226 \end{code}
227
228 @toCalendarTime@ {\em t} converts {\em t} to a local time, modified by
229 the current timezone and daylight savings time settings.  @toUTCTime@
230 {\em t} converts {\em t} into UTC time.  @toClockTime@ {\em l}
231 converts {\em l} into the corresponding internal @ClockTime@.  The
232 {\em wday}, {\em yday}, {\em tzname}, and {\em isdst} fields are
233 ignored.
234
235 \begin{code}
236 toCalendarTime :: ClockTime -> IO CalendarTime
237 toCalendarTime (TOD sec@(J# a# s# d#) psec) = do
238     res    <- allocWords (``sizeof(struct tm)''::Int)
239     zoneNm <- allocChars 32
240     _casm_ ``SETZONE((struct tm *)%0,(char *)%1); '' res zoneNm
241     tm     <- _ccall_ toLocalTime (I# s#) d# res
242     if tm == nullAddr
243      then constructErrorAndFail "Time.toCalendarTime: out of range"
244      else do
245        sec   <-  _casm_ ``%r = ((struct tm *)%0)->tm_sec;'' tm
246        min   <-  _casm_ ``%r = ((struct tm *)%0)->tm_min;'' tm
247        hour  <-  _casm_ ``%r = ((struct tm *)%0)->tm_hour;'' tm
248        mday  <-  _casm_ ``%r = ((struct tm *)%0)->tm_mday;'' tm
249        mon   <-  _casm_ ``%r = ((struct tm *)%0)->tm_mon;'' tm
250        year  <-  _casm_ ``%r = ((struct tm *)%0)->tm_year;'' tm
251        wday  <-  _casm_ ``%r = ((struct tm *)%0)->tm_wday;'' tm
252        yday  <-  _casm_ ``%r = ((struct tm *)%0)->tm_yday;'' tm
253        isdst <-  _casm_ ``%r = ((struct tm *)%0)->tm_isdst;'' tm
254        zone  <-  _ccall_ ZONE tm
255        tz    <-  _ccall_ GMTOFF tm
256        let tzname = unpackCString zone
257        return (CalendarTime (1900+year) mon mday hour min sec psec 
258                             (toEnum wday) yday tzname tz (isdst /= 0))
259
260 toUTCTime :: ClockTime -> CalendarTime
261 toUTCTime  (TOD sec@(J# a# s# d#) psec) = unsafePerformIO $ do
262        res    <- allocWords (``sizeof(struct tm)''::Int)
263        zoneNm <- allocChars 32
264        _casm_ ``SETZONE((struct tm *)%0,(char *)%1); '' res zoneNm
265        tm     <-  _ccall_ toUTCTime (I# s#) d# res
266        if tm == (``NULL''::Addr) 
267         then error "Time.toUTCTime: out of range"
268         else do
269             sec   <- _casm_ ``%r = ((struct tm *)%0)->tm_sec;'' tm
270             min   <- _casm_ ``%r = ((struct tm *)%0)->tm_min;'' tm
271             hour  <- _casm_ ``%r = ((struct tm *)%0)->tm_hour;'' tm
272             mday  <- _casm_ ``%r = ((struct tm *)%0)->tm_mday;'' tm
273             mon   <- _casm_ ``%r = ((struct tm *)%0)->tm_mon;'' tm
274             year  <- _casm_ ``%r = ((struct tm *)%0)->tm_year;'' tm
275             wday  <- _casm_ ``%r = ((struct tm *)%0)->tm_wday;'' tm
276             yday  <- _casm_ ``%r = ((struct tm *)%0)->tm_yday;'' tm
277             return (CalendarTime (1900+year) mon mday hour min sec psec 
278                           (toEnum wday) yday "UTC" 0 False)
279
280 toClockTime :: CalendarTime -> ClockTime
281 toClockTime (CalendarTime year mon mday hour min sec psec wday yday tzname tz isdst) =
282     if psec < 0 || psec > 999999999999 then
283         error "Time.toClockTime: picoseconds out of range"
284     else if tz < -43200 || tz > 43200 then
285         error "Time.toClockTime: timezone offset out of range"
286     else
287         unsafePerformIO ( do
288             res <- allocWords (``sizeof(time_t)'')
289             ptr <- _ccall_ toClockSec year mon mday hour min sec isDst res
290             let (A# ptr#) = ptr
291             if ptr /= ``NULL''
292              then return (TOD (int2Integer# (indexIntOffAddr# ptr# 0#)) psec)
293              else error "Time.toClockTime: can't perform conversion"
294         )
295     where
296      isDst = if isdst then (1::Int) else 0
297
298 bottom :: (Int,Int)
299 bottom = error "Time.bottom"
300
301
302 -- (copied from PosixUtil, for now)
303 -- Allocate a mutable array of characters with no indices.
304
305 allocChars :: Int -> IO (MutableByteArray RealWorld ())
306 allocChars (I# size#) = IO $ \ s# ->
307     case newCharArray# size# s# of 
308       StateAndMutableByteArray# s2# barr# -> 
309         IOok s2# (MutableByteArray bot barr#)
310   where
311     bot = error "Time.allocChars"
312
313 -- Allocate a mutable array of words with no indices
314
315 allocWords :: Int -> IO (MutableByteArray RealWorld ())
316 allocWords (I# size#) = IO $ \ s# ->
317     case newIntArray# size# s# of 
318       StateAndMutableByteArray# s2# barr# -> 
319         IOok s2# (MutableByteArray bot barr#)
320   where
321     bot = error "Time.allocWords"
322
323 \end{code}
324
325 \begin{code}
326 calendarTimeToString  :: CalendarTime -> String
327 calendarTimeToString  =  formatCalendarTime defaultTimeLocale "%c"
328
329 formatCalendarTime :: TimeLocale -> String -> CalendarTime -> String
330 formatCalendarTime l fmt ct@(CalendarTime year mon day hour min sec sdec 
331                                            wday yday tzname _ _) =
332         doFmt fmt
333   where doFmt ('%':c:cs) = decode c ++ doFmt cs
334         doFmt (c:cs) = c : doFmt cs
335         doFmt "" = ""
336
337         decode 'A' = fst (wDays l  !! fromEnum wday)
338         decode 'a' = snd (wDays l  !! fromEnum wday)
339         decode 'B' = fst (months l !! fromEnum mon)
340         decode 'b' = snd (months l !! fromEnum mon)
341         decode 'h' = snd (months l !! fromEnum mon)
342         decode 'C' = show2 (year `quot` 100)
343         decode 'c' = doFmt (dateTimeFmt l)
344         decode 'D' = doFmt "%m/%d/%y"
345         decode 'd' = show2 day
346         decode 'e' = show2' day
347         decode 'H' = show2 hour
348         decode 'I' = show2 (to12 hour)
349         decode 'j' = show3 yday
350         decode 'k' = show2' hour
351         decode 'l' = show2' (to12 hour)
352         decode 'M' = show2 min
353         decode 'm' = show2 (fromEnum mon+1)
354         decode 'n' = "\n"
355         decode 'p' = (if hour < 12 then fst else snd) (amPm l)
356         decode 'R' = doFmt "%H:%M"
357         decode 'r' = doFmt (time12Fmt l)
358         decode 'T' = doFmt "%H:%M:%S"
359         decode 't' = "\t"
360         decode 'S' = show2 sec
361         decode 's' = show2 sec -- Implementation-dependent, sez the lib doc..
362         decode 'U' = show2 ((yday + 7 - fromEnum wday) `div` 7)
363         decode 'u' = show (let n = fromEnum wday in 
364                            if n == 0 then 7 else n)
365         decode 'V' = 
366             let (week, days) = 
367                    (yday + 7 - if fromEnum wday > 0 then 
368                                fromEnum wday - 1 else 6) `divMod` 7
369             in  show2 (if days >= 4 then
370                           week+1 
371                        else if week == 0 then 53 else week)
372
373         decode 'W' = 
374             show2 ((yday + 7 - if fromEnum wday > 0 then 
375                                fromEnum wday - 1 else 6) `div` 7)
376         decode 'w' = show (fromEnum wday)
377         decode 'X' = doFmt (timeFmt l)
378         decode 'x' = doFmt (dateFmt l)
379         decode 'Y' = show year
380         decode 'y' = show2 (year `rem` 100)
381         decode 'Z' = tzname
382         decode '%' = "%"
383         decode c   = [c]
384
385 show2, show2', show3 :: Int -> String
386 show2 x = [intToDigit (x `quot` 10), intToDigit (x `rem` 10)]
387
388 show2' x = if x < 10 then [ ' ', intToDigit x] else show2 x
389
390 show3 x = intToDigit (x `quot` 100) : show2 (x `rem` 100)
391
392 to12 h = let h' = h `mod` 12 in if h == 0 then 12 else h
393 \end{code}
394
395 \begin{code}
396 timeDiffToString :: TimeDiff -> String
397 timeDiffToString = formatTimeDiff defaultTimeLocale "%c"
398
399 formatTimeDiff :: TimeLocale -> String -> TimeDiff -> String
400 formatTimeDiff l fmt ct@(TimeDiff year month day hour min sec psec)
401  = doFmt fmt
402   where 
403    doFmt ""         = ""
404    doFmt ('%':c:cs) = decode c ++ doFmt cs
405    doFmt (c:cs)     = c : doFmt cs
406
407    decode spec =
408     case spec of
409       'B' -> fst (months l !! fromEnum month)
410       'b' -> snd (months l !! fromEnum month)
411       'h' -> snd (months l !! fromEnum month)
412       'C' -> show2 (year `quot` 100)
413       'D' -> doFmt "%m/%d/%y"
414       'd' -> show2 day
415       'e' -> show2' day
416       'H' -> show2 hour
417       'I' -> show2 (to12 hour)
418       'k' -> show2' hour
419       'l' -> show2' (to12 hour)
420       'M' -> show2 min
421       'm' -> show2 (fromEnum month + 1)
422       'n' -> "\n"
423       'p' -> (if hour < 12 then fst else snd) (amPm l)
424       'R' -> doFmt "%H:%M"
425       'r' -> doFmt (time12Fmt l)
426       'T' -> doFmt "%H:%M:%S"
427       't' -> "\t"
428       'S' -> show2 sec
429       's' -> show2 sec -- Implementation-dependent, sez the lib doc..
430       'X' -> doFmt (timeFmt l)
431       'x' -> doFmt (dateFmt l)
432       'Y' -> show year
433       'y' -> show2 (year `rem` 100)
434       '%' -> "%"
435       c   -> [c]
436
437 \end{code}