2 % (c) The GRASP/AQUA Project, Glasgow University, 1995-99
4 \section[Time]{Haskell 1.4 Time of Day Library}
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).
12 {-# OPTIONS -#include "cbits/timezone.h" -#include "cbits/stgio.h" #-}
18 , ClockTime(..) -- non-standard, lib. report gives this as abstract
25 , timeDiffToString -- non-standard
26 , formatTimeDiff -- non-standard
32 , calendarTimeToString
46 import PrelPack ( unpackCString )
50 import Char ( intToDigit )
55 One way to partition and give name to chunks of a year and a week:
59 = January | February | March | April
60 | May | June | July | August
61 | September | October | November | December
62 deriving (Eq, Ord, Enum, Bounded, Ix, Read, Show)
65 = Sunday | Monday | Tuesday | Wednesday
66 | Thursday | Friday | Saturday
67 deriving (Eq, Ord, Enum, Bounded, Ix, Read, Show)
71 @ClockTime@ is an abstract type, used for the internal clock time.
72 Clock times may be compared, converted to strings, or converted to an
73 external calendar time @CalendarTime@.
77 -- I believe Int64 is more than big enough.
78 -- In fact, I think one of Int32 or Word32 would do. - ADR
79 data ClockTime = TOD Int64 Int64 deriving (Eq, Ord)
81 data ClockTime = TOD Integer Integer deriving (Eq, Ord)
85 When a @ClockTime@ is shown, it is converted to a string of the form
86 @"Mon Nov 28 21:45:41 GMT 1994"@.
88 For now, we are restricted to roughly:
89 Fri Dec 13 20:45:52 1901 through Tue Jan 19 03:14:07 2038, because
90 we use the C library routines based on 32 bit integers.
94 #warning Show ClockTime is bogus
95 instance Show ClockTime
97 instance Show ClockTime where
98 showsPrec _ (TOD (J# _ s# d#) _nsec) =
99 showString $ unsafePerformIO $ do
100 buf <- allocChars 38 -- exactly enough for error message
101 str <- _ccall_ showTime (I# s#) d# buf
102 return (unpackCString str)
104 showList = showList__ (showsPrec 0)
109 @CalendarTime@ is a user-readable and manipulable
110 representation of the internal $ClockTime$ type. The
111 numeric fields have the following ranges.
117 year -maxInt .. maxInt [Pre-Gregorian dates are inaccurate]
118 mon 0 .. 11 [Jan = 0, Dec = 11]
122 sec 0 .. 61 [Allows for two leap seconds]
123 picosec 0 .. (10^12)-1 [This could be over-precise?]
124 wday 0 .. 6 [Sunday = 0, Saturday = 6]
125 yday 0 .. 365 [364 in non-Leap years]
126 tz -43200 .. 43200 [Variation from UTC in seconds]
129 The {\em tzname} field is the name of the time zone. The {\em isdst}
130 field indicates whether Daylight Savings Time would be in effect.
144 ctPicosec :: Integer,
152 deriving (Eq,Ord,Read,Show)
156 The @TimeDiff@ type records the difference between two clock times in
169 tdPicosec :: Int64 -- not standard
171 tdPicosec :: Integer -- not standard
174 deriving (Eq,Ord,Read,Show)
177 @getClockTime@ returns the current time in its internal representation.
181 getClockTime :: IO ClockTime
185 rc <- prim_getClockTime i1 i2
188 sec <- cvtUnsigned i1
189 nsec <- cvtUnsigned i2
190 return (TOD sec (nsec * 1000))
192 constructErrorAndFail "getClockTime"
194 malloc1 = primNewByteArray sizeof_int64
195 cvtUnsigned arr = primReadInt64Array arr 0
197 getClockTime :: IO ClockTime
201 rc <- _ccall_ getClockTime i1 i2
204 sec <- cvtUnsigned i1
205 nsec <- cvtUnsigned i2
206 return (TOD sec (nsec * 1000))
208 constructErrorAndFail "getClockTime"
210 malloc1 = IO $ \ s# ->
211 case newIntArray# 1# s# of
213 (# s2#, MutableByteArray bottom barr# #)
215 -- The C routine fills in an unsigned word. We don't have
216 -- `unsigned2Integer#,' so we freeze the data bits and use them
217 -- for an MP_INT structure. Note that zero is still handled specially,
218 -- although (J# 1# 1# (ptr to 0#)) is probably acceptable to gmp.
220 cvtUnsigned (MutableByteArray _ arr#) = IO $ \ s# ->
221 case readIntArray# arr# 0# s# of
225 else case unsafeFreezeByteArray# arr# s2# of
226 (# s3#, frozen# #) ->
227 (# s3#, J# 1# 1# frozen# #)
231 @addToClockTime@ {\em d} {\em t} adds a time difference {\em d} and a
232 clock time {\em t} to yield a new clock time. The difference {\em d}
233 may be either positive or negative. @[diffClockTimes@ {\em t1} {\em
234 t2} returns the difference between two clock times {\em t1} and {\em
240 addToClockTime :: TimeDiff -> ClockTime -> ClockTime
241 addToClockTime (TimeDiff year mon day hour min sec psec)
242 (TOD c_sec c_psec) = unsafePerformIO $ do
243 res <- allocWords sizeof_int64
244 rc <- prim_toClockSec year mon day hour min sec 0 res
247 diff_sec <- primReadInt64Array res 0
249 return (TOD (c_sec + diff_sec) (c_psec + diff_psec))
251 error "Time.addToClockTime: can't perform conversion of TimeDiff"
253 addToClockTime :: TimeDiff -> ClockTime -> ClockTime
254 addToClockTime (TimeDiff year mon day hour min sec psec)
255 (TOD c_sec c_psec) = unsafePerformIO $ do
256 res <- allocWords (``sizeof(time_t)'')
257 ptr <- _ccall_ toClockSec year mon day hour min sec (0::Int) res
261 diff_sec = (int2Integer (indexIntOffAddr# ptr# 0#))
264 return (TOD (c_sec + diff_sec) (c_psec + diff_psec))
266 error "Time.addToClockTime: can't perform conversion of TimeDiff"
269 diffClockTimes :: ClockTime -> ClockTime -> TimeDiff
270 diffClockTimes tod_a tod_b =
272 CalendarTime year_a mon_a day_a hour_a min_a sec_a psec_a _ _ _ _ _ = toUTCTime tod_a
273 CalendarTime year_b mon_b day_b hour_b min_b sec_b psec_b _ _ _ _ _ = toUTCTime tod_b
275 TimeDiff (year_a - year_b)
284 @toCalendarTime@ {\em t} converts {\em t} to a local time, modified by
285 the current timezone and daylight savings time settings. @toUTCTime@
286 {\em t} converts {\em t} into UTC time. @toClockTime@ {\em l}
287 converts {\em l} into the corresponding internal @ClockTime@. The
288 {\em wday}, {\em yday}, {\em tzname}, and {\em isdst} fields are
293 toCalendarTime :: ClockTime -> IO CalendarTime
294 toCalendarTime (TOD sec psec) = do
295 res <- allocWords sizeof_int64
296 zoneNm <- allocChars 32
297 prim_SETZONE res zoneNm
298 rc <- prim_toLocalTime sec res
300 then constructErrorAndFail "Time.toCalendarTime: out of range"
302 sec <- get_tm_sec res
303 min <- get_tm_min res
304 hour <- get_tm_hour res
305 mday <- get_tm_mday res
306 mon <- get_tm_mon res
307 year <- get_tm_year res
308 wday <- get_tm_wday res
309 yday <- get_tm_yday res
310 isdst <- get_tm_isdst res
311 zone <- prim_ZONE res
312 tz <- prim_GMTOFF res
313 tzname <- primUnpackCString zone
314 return (CalendarTime (1900+year) mon mday hour min sec psec
315 (toEnum wday) yday tzname tz (isdst /= 0))
317 toUTCTime :: ClockTime -> CalendarTime
318 toUTCTime (TOD sec psec) = unsafePerformIO $ do
319 res <- allocWords sizeof_int64
320 zoneNm <- allocChars 32
321 prim_SETZONE res zoneNm
322 rc <- prim_toUTCTime sec res
324 then error "Time.toUTCTime: out of range"
326 sec <- get_tm_sec res
327 min <- get_tm_min res
328 hour <- get_tm_hour res
329 mday <- get_tm_mday res
330 mon <- get_tm_mon res
331 year <- get_tm_year res
332 wday <- get_tm_wday res
333 yday <- get_tm_yday res
334 return (CalendarTime (1900+year) mon mday hour min sec psec
335 (toEnum wday) yday "UTC" 0 False)
337 toClockTime :: CalendarTime -> ClockTime
338 toClockTime (CalendarTime year mon mday hour min sec psec wday yday tzname tz isdst) =
339 if psec < 0 || psec > 999999999999 then
340 error "Time.toClockTime: picoseconds out of range"
341 else if tz < -43200 || tz > 43200 then
342 error "Time.toClockTime: timezone offset out of range"
345 res <- allocWords sizeof_int64
346 rc <- prim_toClockSec year mon mday hour min sec isDst res
349 tm <- primReadInt64Array res 0
351 else error "Time.toClockTime: can't perform conversion"
354 isDst = if isdst then (1::Int) else 0
356 toCalendarTime :: ClockTime -> IO CalendarTime
357 toCalendarTime (TOD (J# _ s# d#) psec) = do
358 res <- allocWords (``sizeof(struct tm)''::Int)
359 zoneNm <- allocChars 32
360 _casm_ ``SETZONE((struct tm *)%0,(char *)%1); '' res zoneNm
361 tm <- _ccall_ toLocalTime (I# s#) d# res
363 then constructErrorAndFail "Time.toCalendarTime: out of range"
365 sec <- _casm_ ``%r = ((struct tm *)%0)->tm_sec;'' tm
366 min <- _casm_ ``%r = ((struct tm *)%0)->tm_min;'' tm
367 hour <- _casm_ ``%r = ((struct tm *)%0)->tm_hour;'' tm
368 mday <- _casm_ ``%r = ((struct tm *)%0)->tm_mday;'' tm
369 mon <- _casm_ ``%r = ((struct tm *)%0)->tm_mon;'' tm
370 year <- _casm_ ``%r = ((struct tm *)%0)->tm_year;'' tm
371 wday <- _casm_ ``%r = ((struct tm *)%0)->tm_wday;'' tm
372 yday <- _casm_ ``%r = ((struct tm *)%0)->tm_yday;'' tm
373 isdst <- _casm_ ``%r = ((struct tm *)%0)->tm_isdst;'' tm
374 zone <- _ccall_ ZONE tm
375 tz <- _ccall_ GMTOFF tm
376 let tzname = unpackCString zone
377 return (CalendarTime (1900+year) mon mday hour min sec psec
378 (toEnum wday) yday tzname tz (isdst /= (0::Int)))
380 toUTCTime :: ClockTime -> CalendarTime
381 toUTCTime (TOD (J# _ s# d#) psec) = unsafePerformIO $ do
382 res <- allocWords (``sizeof(struct tm)''::Int)
383 zoneNm <- allocChars 32
384 _casm_ ``SETZONE((struct tm *)%0,(char *)%1); '' res zoneNm
385 tm <- _ccall_ toUTCTime (I# s#) d# res
387 then error "Time.toUTCTime: out of range"
389 sec <- _casm_ ``%r = ((struct tm *)%0)->tm_sec;'' tm
390 min <- _casm_ ``%r = ((struct tm *)%0)->tm_min;'' tm
391 hour <- _casm_ ``%r = ((struct tm *)%0)->tm_hour;'' tm
392 mday <- _casm_ ``%r = ((struct tm *)%0)->tm_mday;'' tm
393 mon <- _casm_ ``%r = ((struct tm *)%0)->tm_mon;'' tm
394 year <- _casm_ ``%r = ((struct tm *)%0)->tm_year;'' tm
395 wday <- _casm_ ``%r = ((struct tm *)%0)->tm_wday;'' tm
396 yday <- _casm_ ``%r = ((struct tm *)%0)->tm_yday;'' tm
397 return (CalendarTime (1900+year) mon mday hour min sec psec
398 (toEnum wday) yday "UTC" 0 False)
400 toClockTime :: CalendarTime -> ClockTime
401 toClockTime (CalendarTime year mon mday hour min sec psec _wday _yday _tzname tz isdst) =
402 if psec < 0 || psec > 999999999999 then
403 error "Time.toClockTime: picoseconds out of range"
404 else if tz < -43200 || tz > 43200 then
405 error "Time.toClockTime: timezone offset out of range"
408 res <- allocWords (``sizeof(time_t)'')
409 ptr <- _ccall_ toClockSec year mon mday hour min sec isDst res
412 then return (TOD (int2Integer (indexIntOffAddr# ptr# 0#)) psec)
413 else error "Time.toClockTime: can't perform conversion"
416 isDst = if isdst then (1::Int) else 0
420 bottom = error "Time.bottom"
423 -- (copied from PosixUtil, for now)
424 -- Allocate a mutable array of characters with no indices.
427 allocChars :: Int -> IO (PrimMutableByteArray RealWorld)
428 allocChars size = primNewByteArray size
430 -- Allocate a mutable array of words with no indices
432 allocWords :: Int -> IO (PrimMutableByteArray RealWorld)
433 allocWords size = primNewByteArray size
435 allocChars :: Int -> IO (MutableByteArray RealWorld ())
436 allocChars (I# size#) = IO $ \ s# ->
437 case newCharArray# size# s# of
439 (# s2#, MutableByteArray bot barr# #)
441 bot = error "Time.allocChars"
443 -- Allocate a mutable array of words with no indices
445 allocWords :: Int -> IO (MutableByteArray RealWorld ())
446 allocWords (I# size#) = IO $ \ s# ->
447 case newIntArray# size# s# of
449 (# s2#, MutableByteArray bot barr# #)
451 bot = error "Time.allocWords"
456 calendarTimeToString :: CalendarTime -> String
457 calendarTimeToString = formatCalendarTime defaultTimeLocale "%c"
459 formatCalendarTime :: TimeLocale -> String -> CalendarTime -> String
460 formatCalendarTime l fmt (CalendarTime year mon day hour min sec _
461 wday yday tzname _ _) =
463 where doFmt ('%':c:cs) = decode c ++ doFmt cs
464 doFmt (c:cs) = c : doFmt cs
467 decode 'A' = fst (wDays l !! fromEnum wday) -- day of the week, full name
468 decode 'a' = snd (wDays l !! fromEnum wday) -- day of the week, abbrev.
469 decode 'B' = fst (months l !! fromEnum mon) -- month, full name
470 decode 'b' = snd (months l !! fromEnum mon) -- month, abbrev
471 decode 'h' = snd (months l !! fromEnum mon) -- ditto
472 decode 'C' = show2 (year `quot` 100) -- century
473 decode 'c' = doFmt (dateTimeFmt l) -- locale's data and time format.
474 decode 'D' = doFmt "%m/%d/%y"
475 decode 'd' = show2 day -- day of the month
476 decode 'e' = show2' day -- ditto, padded
477 decode 'H' = show2 hour -- hours, 24-hour clock, padded
478 decode 'I' = show2 (to12 hour) -- hours, 12-hour clock
479 decode 'j' = show3 yday -- day of the year
480 decode 'k' = show2' hour -- hours, 24-hour clock, no padding
481 decode 'l' = show2' (to12 hour) -- hours, 12-hour clock, no padding
482 decode 'M' = show2 min -- minutes
483 decode 'm' = show2 (fromEnum mon+1) -- numeric month
485 decode 'p' = (if hour < 12 then fst else snd) (amPm l) -- am or pm
486 decode 'R' = doFmt "%H:%M"
487 decode 'r' = doFmt (time12Fmt l)
488 decode 'T' = doFmt "%H:%M:%S"
490 decode 'S' = show2 sec -- seconds
491 decode 's' = show2 sec -- number of secs since Epoch. (ToDo.)
492 decode 'U' = show2 ((yday + 7 - fromEnum wday) `div` 7) -- week number, starting on Sunday.
493 decode 'u' = show (let n = fromEnum wday in -- numeric day of the week (1=Monday, 7=Sunday)
494 if n == 0 then 7 else n)
495 decode 'V' = -- week number (as per ISO-8601.)
496 let (week, days) = -- [yep, I've always wanted to be able to display that too.]
497 (yday + 7 - if fromEnum wday > 0 then
498 fromEnum wday - 1 else 6) `divMod` 7
499 in show2 (if days >= 4 then
501 else if week == 0 then 53 else week)
503 decode 'W' = -- week number, weeks starting on monday
504 show2 ((yday + 7 - if fromEnum wday > 0 then
505 fromEnum wday - 1 else 6) `div` 7)
506 decode 'w' = show (fromEnum wday) -- numeric day of the week, weeks starting on Sunday.
507 decode 'X' = doFmt (timeFmt l) -- locale's preferred way of printing time.
508 decode 'x' = doFmt (dateFmt l) -- locale's preferred way of printing dates.
509 decode 'Y' = show year -- year, including century.
510 decode 'y' = show2 (year `rem` 100) -- year, within century.
511 decode 'Z' = tzname -- timezone name
516 show2, show2', show3 :: Int -> String
517 show2 x = [intToDigit (x `quot` 10), intToDigit (x `rem` 10)]
519 show2' x = if x < 10 then [ ' ', intToDigit x] else show2 x
521 show3 x = intToDigit (x `quot` 100) : show2 (x `rem` 100)
524 to12 h = let h' = h `mod` 12 in if h' == 0 then 12 else h'
527 Useful extensions for formatting TimeDiffs.
530 timeDiffToString :: TimeDiff -> String
531 timeDiffToString = formatTimeDiff defaultTimeLocale "%c"
533 formatTimeDiff :: TimeLocale -> String -> TimeDiff -> String
534 formatTimeDiff l fmt (TimeDiff year month day hour min sec _)
538 doFmt ('%':c:cs) = decode c ++ doFmt cs
539 doFmt (c:cs) = c : doFmt cs
543 'B' -> fst (months l !! fromEnum month)
544 'b' -> snd (months l !! fromEnum month)
545 'h' -> snd (months l !! fromEnum month)
546 'C' -> show2 (year `quot` 100)
547 'D' -> doFmt "%m/%d/%y"
551 'I' -> show2 (to12 hour)
553 'l' -> show2' (to12 hour)
555 'm' -> show2 (fromEnum month + 1)
557 'p' -> (if hour < 12 then fst else snd) (amPm l)
559 'r' -> doFmt (time12Fmt l)
560 'T' -> doFmt "%H:%M:%S"
563 's' -> show2 sec -- Implementation-dependent, sez the lib doc..
564 'X' -> doFmt (timeFmt l)
565 'x' -> doFmt (dateFmt l)
567 'y' -> show2 (year `rem` 100)
575 foreign import stdcall "libHS_cbits.so" "get_tm_sec" get_tm_sec :: Bytes -> IO Int
576 foreign import stdcall "libHS_cbits.so" "get_tm_min" get_tm_min :: Bytes -> IO Int
577 foreign import stdcall "libHS_cbits.so" "get_tm_hour" get_tm_hour :: Bytes -> IO Int
578 foreign import stdcall "libHS_cbits.so" "get_tm_mday" get_tm_mday :: Bytes -> IO Int
579 foreign import stdcall "libHS_cbits.so" "get_tm_mon" get_tm_mon :: Bytes -> IO Int
580 foreign import stdcall "libHS_cbits.so" "get_tm_year" get_tm_year :: Bytes -> IO Int
581 foreign import stdcall "libHS_cbits.so" "get_tm_wday" get_tm_wday :: Bytes -> IO Int
582 foreign import stdcall "libHS_cbits.so" "get_tm_yday" get_tm_yday :: Bytes -> IO Int
583 foreign import stdcall "libHS_cbits.so" "get_tm_isdst" get_tm_isdst :: Bytes -> IO Int
585 foreign import stdcall "libHS_cbits.so" "prim_ZONE" prim_ZONE :: Bytes -> IO Addr
586 foreign import stdcall "libHS_cbits.so" "prim_GMTOFF" prim_GMTOFF :: Bytes -> IO Int
588 foreign import stdcall "libHS_cbits.so" "prim_SETZONE" prim_SETZONE :: Bytes -> Bytes -> IO Int
590 foreign import stdcall "libHS_cbits.so" "sizeof_word" sizeof_word :: Int
591 foreign import stdcall "libHS_cbits.so" "sizeof_struct_tm" sizeof_struct_tm :: Int
592 foreign import stdcall "libHS_cbits.so" "sizeof_time_t" sizeof_time_t :: Int
594 -- believed to be at least 1 bit (the sign bit!) bigger than sizeof_time_t
598 foreign import stdcall "libHS_cbits.so" "prim_getClockTime" prim_getClockTime :: Bytes -> Bytes -> IO Int
599 foreign import stdcall "libHS_cbits.so" "prim_toClockSec" prim_toClockSec :: Int -> Int -> Int -> Int -> Int -> Int -> Int -> Bytes -> IO Int
600 foreign import stdcall "libHS_cbits.so" "prim_toLocalTime" prim_toLocalTime :: Int64 -> Bytes -> IO Int
601 foreign import stdcall "libHS_cbits.so" "prim_toUTCTime" prim_toUTCTime :: Int64 -> Bytes -> IO Int