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
22 , noTimeDiff -- non-standard (but useful when constructing TimeDiff vals.)
26 , timeDiffToString -- non-standard
27 , formatTimeDiff -- non-standard
33 , calendarTimeToString
49 import PrelPack ( unpackCString, new_ps_array,
50 freeze_ps_array, unpackCStringBA
55 import Char ( intToDigit )
60 One way to partition and give name to chunks of a year and a week:
64 = January | February | March | April
65 | May | June | July | August
66 | September | October | November | December
67 deriving (Eq, Ord, Enum, Bounded, Ix, Read, Show)
70 = Sunday | Monday | Tuesday | Wednesday
71 | Thursday | Friday | Saturday
72 deriving (Eq, Ord, Enum, Bounded, Ix, Read, Show)
76 @ClockTime@ is an abstract type, used for the internal clock time.
77 Clock times may be compared, converted to strings, or converted to an
78 external calendar time @CalendarTime@.
82 -- I believe Int64 is more than big enough.
83 -- In fact, I think one of Int32 or Word32 would do. - ADR
84 data ClockTime = TOD Int64 Int64 deriving (Eq, Ord)
86 data ClockTime = TOD Integer -- Seconds since 00:00:00 on 1 Jan 1970
87 Integer -- Picoseconds with the specified second
93 When a @ClockTime@ is shown, it is converted to a string of the form
94 @"Mon Nov 28 21:45:41 GMT 1994"@.
96 For now, we are restricted to roughly:
97 Fri Dec 13 20:45:52 1901 through Tue Jan 19 03:14:07 2038, because
98 we use the C library routines based on 32 bit integers.
102 #warning Show ClockTime is bogus
103 instance Show ClockTime
105 instance Show ClockTime where
106 showsPrec p (TOD (S# i) _nsec) =
107 case int2Integer# i of (# s, d #) -> showsPrec p (TOD (J# s d) _nsec)
108 showsPrec _ (TOD (J# s# d#) _nsec) =
109 showString $ unsafePerformIO $ do
110 let buflen@(I# buflen#) = 50 -- big enough for error message
111 buf <- allocChars buflen
112 if s# <# (negateInt# 1#) || s# ># 1# then
113 return "ClockTime.show{Time}: out of range"
115 rc <- showTime (I# s#) d# buflen buf
117 return "ClockTime.show{Time}: internal error"
119 ba <- stToIO (freeze_ps_array buf buflen#)
120 return (unpackCStringBA ba)
122 showList = showList__ (showsPrec 0)
127 @CalendarTime@ is a user-readable and manipulable
128 representation of the internal $ClockTime$ type. The
129 numeric fields have the following ranges.
135 year -maxInt .. maxInt [Pre-Gregorian dates are inaccurate]
136 mon 0 .. 11 [Jan = 0, Dec = 11]
140 sec 0 .. 61 [Allows for two leap seconds]
141 picosec 0 .. (10^12)-1 [This could be over-precise?]
142 wday 0 .. 6 [Sunday = 0, Saturday = 6]
143 yday 0 .. 365 [364 in non-Leap years]
144 tz -43200 .. 43200 [Variation from UTC in seconds]
147 The {\em tzname} field is the name of the time zone. The {\em isdst}
148 field indicates whether Daylight Savings Time would be in effect.
162 ctPicosec :: Integer,
170 deriving (Eq,Ord,Read,Show)
174 The @TimeDiff@ type records the difference between two clock times in
187 tdPicosec :: Int64 -- not standard
189 tdPicosec :: Integer -- not standard
192 deriving (Eq,Ord,Read,Show)
194 noTimeDiff :: TimeDiff
195 noTimeDiff = TimeDiff 0 0 0 0 0 0 0
198 @getClockTime@ returns the current time in its internal representation.
201 getClockTime :: IO ClockTime
205 rc <- primGetClockTime i1 i2
208 sec <- cvtUnsigned i1
209 nsec <- cvtUnsigned i2
210 return (TOD sec (nsec * 1000))
212 constructErrorAndFail "getClockTime"
215 malloc1 = primNewByteArray sizeof_int64
216 cvtUnsigned arr = primReadInt64Array arr 0
218 malloc1 :: IO (MutableByteArray RealWorld Int)
219 malloc1 = IO $ \ s# ->
220 case newIntArray# 1# s# of
221 (# s2#, barr# #) -> (# s2#, MutableByteArray bot bot barr# #)
223 bot = error "Time.malloc1"
225 -- The C routine fills in an unsigned word. We don't have
226 -- `unsigned2Integer#,' so we freeze the data bits and use them
227 -- for an MP_INT structure. Note that zero is still handled specially,
228 -- although (J# 1# (ptr to 0#)) is probably acceptable to gmp.
230 cvtUnsigned :: MutableByteArray RealWorld Int -> IO Integer
231 cvtUnsigned (MutableByteArray _ _ arr#) = IO $ \ s# ->
232 case readIntArray# arr# 0# s# of
233 (# s2#, r# #) | r# ==# 0# -> (# s2#, 0 #)
235 case unsafeFreezeByteArray# arr# s2# of
236 (# s3#, frozen# #) -> (# s3#, J# 1# frozen# #)
240 @addToClockTime@ {\em d} {\em t} adds a time difference {\em d} and a
241 clock time {\em t} to yield a new clock time. The difference {\em d}
242 may be either positive or negative. @[diffClockTimes@ {\em t1} {\em
243 t2} returns the difference between two clock times {\em t1} and {\em
248 addToClockTime :: TimeDiff -> ClockTime -> ClockTime
249 addToClockTime (TimeDiff year mon day hour min sec psec)
252 sec_diff = fromInt sec + 60 * fromInt min + 3600 * fromInt hour + 24 * 3600 * fromInt day
253 cal = toUTCTime (TOD (c_sec + sec_diff) (c_psec + psec))
255 new_mon = fromEnum (ctMonth cal) + r_mon
257 | new_mon < 0 = (toEnum (12 + new_mon), (-1))
258 | new_mon > 11 = (toEnum (new_mon `mod` 12), 1)
259 | otherwise = (toEnum new_mon, 0)
261 (r_yr, r_mon) = mon `quotRem` 12
263 year' = ctYear cal + year + r_yr + yr_diff
265 toClockTime cal{ctMonth=month', ctYear=year'}
267 diffClockTimes :: ClockTime -> ClockTime -> TimeDiff
268 diffClockTimes tod_a tod_b =
270 CalendarTime year_a mon_a day_a hour_a min_a sec_a psec_a _ _ _ _ _ = toUTCTime tod_a
271 CalendarTime year_b mon_b day_b hour_b min_b sec_b psec_b _ _ _ _ _ = toUTCTime tod_b
273 TimeDiff (year_a - year_b)
274 (fromEnum mon_a - fromEnum mon_b)
282 @toCalendarTime@ {\em t} converts {\em t} to a local time, modified by
283 the current timezone and daylight savings time settings. @toUTCTime@
284 {\em t} converts {\em t} into UTC time. @toClockTime@ {\em l}
285 converts {\em l} into the corresponding internal @ClockTime@. The
286 {\em wday}, {\em yday}, {\em tzname}, and {\em isdst} fields are
291 toCalendarTime :: ClockTime -> IO CalendarTime
292 toCalendarTime (TOD sec psec) = do
293 res <- allocWords sizeof_int64
294 zoneNm <- allocChars 32
295 prim_SETZONE res zoneNm
296 rc <- prim_toLocalTime sec res
298 then constructErrorAndFail "Time.toCalendarTime: out of range"
300 sec <- get_tm_sec res
301 min <- get_tm_min res
302 hour <- get_tm_hour res
303 mday <- get_tm_mday res
304 mon <- get_tm_mon res
305 year <- get_tm_year res
306 wday <- get_tm_wday res
307 yday <- get_tm_yday res
308 isdst <- get_tm_isdst res
309 zone <- prim_ZONE res
310 tz <- prim_GMTOFF res
311 tzname <- primUnpackCString zone
312 return (CalendarTime (1900+year) mon mday hour min sec psec
313 (toEnum wday) yday tzname tz (isdst /= 0))
315 toUTCTime :: ClockTime -> CalendarTime
316 toUTCTime (TOD sec psec) = unsafePerformIO $ do
317 res <- allocWords sizeof_int64
318 zoneNm <- allocChars 32
319 prim_SETZONE res zoneNm
320 rc <- prim_toUTCTime sec res
322 then error "Time.toUTCTime: out of range"
324 sec <- get_tm_sec res
325 min <- get_tm_min res
326 hour <- get_tm_hour res
327 mday <- get_tm_mday res
328 mon <- get_tm_mon res
329 year <- get_tm_year res
330 wday <- get_tm_wday res
331 yday <- get_tm_yday res
332 return (CalendarTime (1900+year) mon mday hour min sec psec
333 (toEnum wday) yday "UTC" 0 False)
335 toClockTime :: CalendarTime -> ClockTime
336 toClockTime (CalendarTime year mon mday hour min sec psec wday yday tzname tz isdst) =
337 if psec < 0 || psec > 999999999999 then
338 error "Time.toClockTime: picoseconds out of range"
339 else if tz < -43200 || tz > 43200 then
340 error "Time.toClockTime: timezone offset out of range"
343 res <- allocWords sizeof_int64
344 rc <- toClockSec year (fromEnum mon) mday hour min sec isDst res
347 tm <- primReadInt64Array res 0
349 else error "Time.toClockTime: can't perform conversion"
352 isDst = if isdst then (1::Int) else 0
354 toCalendarTime :: ClockTime -> IO CalendarTime
355 toCalendarTime (TOD (S# i) psec)
356 = case int2Integer# i of (# s, d #) -> toCalendarTime (TOD (J# s d) psec)
357 toCalendarTime (TOD (J# s# d#) psec) = do
358 res <- allocWords sizeof_struct_tm
359 zoneNm <- allocChars 32
360 prim_SETZONE res zoneNm
361 rc <- prim_toLocalTime (I# s#) d# res
363 then constructErrorAndFail "Time.toCalendarTime: out of range"
365 sec <- get_tm_sec res
366 min <- get_tm_min res
367 hour <- get_tm_hour res
368 mday <- get_tm_mday res
369 mon <- get_tm_mon res
370 year <- get_tm_year res
371 wday <- get_tm_wday res
372 yday <- get_tm_yday res
373 isdst <- get_tm_isdst res
376 let tzname = unpackCString zone
378 | mon >= 0 && mon <= 11 = toEnum mon
379 | otherwise = error ("toCalendarTime: illegal month value: " ++ show mon)
381 return (CalendarTime (1900+year) month mday hour min sec psec
382 (toEnum wday) yday tzname tz (isdst /= (0::Int)))
384 toUTCTime :: ClockTime -> CalendarTime
385 toUTCTime (TOD (S# i) psec)
386 = case int2Integer# i of (# s, d #) -> toUTCTime (TOD (J# s d) psec)
387 toUTCTime (TOD (J# s# d#) psec) = unsafePerformIO $ do
388 res <- allocWords sizeof_struct_tm
389 zoneNm <- allocChars 32
390 prim_SETZONE res zoneNm
391 rc <- prim_toUTCTime (I# s#) d# res
393 then error "Time.toUTCTime: out of range"
395 sec <- get_tm_sec res
396 min <- get_tm_min res
397 hour <- get_tm_hour res
398 mday <- get_tm_mday res
399 mon <- get_tm_mon res
400 year <- get_tm_year res
401 wday <- get_tm_wday res
402 yday <- get_tm_yday res
405 | mon >= 0 && mon <= 11 = toEnum mon
406 | otherwise = error ("toCalendarTime: illegal month value: " ++ show mon)
408 return (CalendarTime (1900+year) month mday hour min sec psec
409 (toEnum wday) yday "UTC" 0 False)
411 toClockTime :: CalendarTime -> ClockTime
412 toClockTime (CalendarTime year mon mday hour min sec psec _wday _yday _tzname tz isdst) =
413 if psec < 0 || psec > 999999999999 then
414 error "Time.toClockTime: picoseconds out of range"
415 else if tz < -43200 || tz > 43200 then
416 error "Time.toClockTime: timezone offset out of range"
420 rc <- toClockSec year (fromEnum mon) mday hour min sec isDst res
425 else error "Time.toClockTime: can't perform conversion"
428 isDst = if isdst then (1::Int) else 0
432 -- (copied from PosixUtil, for now)
433 -- Allocate a mutable array of characters with no indices.
436 allocChars :: Int -> IO (PrimMutableByteArray RealWorld)
437 allocChars size = primNewByteArray size
439 -- Allocate a mutable array of words with no indices
441 allocWords :: Int -> IO (PrimMutableByteArray RealWorld)
442 allocWords size = primNewByteArray size
444 allocChars :: Int -> IO (MutableByteArray RealWorld Int)
445 allocChars (I# size#) = stToIO (new_ps_array size#)
447 -- Allocate a mutable array of words with no indices
449 allocWords :: Int -> IO (MutableByteArray RealWorld Int)
450 allocWords (I# size#) = IO $ \ s# ->
451 case newIntArray# size# s# of
453 (# s2#, MutableByteArray bot bot barr# #)
455 bot = error "Time.allocWords"
460 calendarTimeToString :: CalendarTime -> String
461 calendarTimeToString = formatCalendarTime defaultTimeLocale "%c"
463 formatCalendarTime :: TimeLocale -> String -> CalendarTime -> String
464 formatCalendarTime l fmt (CalendarTime year mon day hour min sec _
465 wday yday tzname _ _) =
467 where doFmt ('%':c:cs) = decode c ++ doFmt cs
468 doFmt (c:cs) = c : doFmt cs
471 decode 'A' = fst (wDays l !! fromEnum wday) -- day of the week, full name
472 decode 'a' = snd (wDays l !! fromEnum wday) -- day of the week, abbrev.
473 decode 'B' = fst (months l !! fromEnum mon) -- month, full name
474 decode 'b' = snd (months l !! fromEnum mon) -- month, abbrev
475 decode 'h' = snd (months l !! fromEnum mon) -- ditto
476 decode 'C' = show2 (year `quot` 100) -- century
477 decode 'c' = doFmt (dateTimeFmt l) -- locale's data and time format.
478 decode 'D' = doFmt "%m/%d/%y"
479 decode 'd' = show2 day -- day of the month
480 decode 'e' = show2' day -- ditto, padded
481 decode 'H' = show2 hour -- hours, 24-hour clock, padded
482 decode 'I' = show2 (to12 hour) -- hours, 12-hour clock
483 decode 'j' = show3 yday -- day of the year
484 decode 'k' = show2' hour -- hours, 24-hour clock, no padding
485 decode 'l' = show2' (to12 hour) -- hours, 12-hour clock, no padding
486 decode 'M' = show2 min -- minutes
487 decode 'm' = show2 (fromEnum mon+1) -- numeric month
489 decode 'p' = (if hour < 12 then fst else snd) (amPm l) -- am or pm
490 decode 'R' = doFmt "%H:%M"
491 decode 'r' = doFmt (time12Fmt l)
492 decode 'T' = doFmt "%H:%M:%S"
494 decode 'S' = show2 sec -- seconds
495 decode 's' = show2 sec -- number of secs since Epoch. (ToDo.)
496 decode 'U' = show2 ((yday + 7 - fromEnum wday) `div` 7) -- week number, starting on Sunday.
497 decode 'u' = show (let n = fromEnum wday in -- numeric day of the week (1=Monday, 7=Sunday)
498 if n == 0 then 7 else n)
499 decode 'V' = -- week number (as per ISO-8601.)
500 let (week, days) = -- [yep, I've always wanted to be able to display that too.]
501 (yday + 7 - if fromEnum wday > 0 then
502 fromEnum wday - 1 else 6) `divMod` 7
503 in show2 (if days >= 4 then
505 else if week == 0 then 53 else week)
507 decode 'W' = -- week number, weeks starting on monday
508 show2 ((yday + 7 - if fromEnum wday > 0 then
509 fromEnum wday - 1 else 6) `div` 7)
510 decode 'w' = show (fromEnum wday) -- numeric day of the week, weeks starting on Sunday.
511 decode 'X' = doFmt (timeFmt l) -- locale's preferred way of printing time.
512 decode 'x' = doFmt (dateFmt l) -- locale's preferred way of printing dates.
513 decode 'Y' = show year -- year, including century.
514 decode 'y' = show2 (year `rem` 100) -- year, within century.
515 decode 'Z' = tzname -- timezone name
520 show2, show2', show3 :: Int -> String
521 show2 x = [intToDigit (x `quot` 10), intToDigit (x `rem` 10)]
523 show2' x = if x < 10 then [ ' ', intToDigit x] else show2 x
525 show3 x = intToDigit (x `quot` 100) : show2 (x `rem` 100)
528 to12 h = let h' = h `mod` 12 in if h' == 0 then 12 else h'
531 Useful extensions for formatting TimeDiffs.
534 timeDiffToString :: TimeDiff -> String
535 timeDiffToString = formatTimeDiff defaultTimeLocale "%c"
537 formatTimeDiff :: TimeLocale -> String -> TimeDiff -> String
538 formatTimeDiff l fmt (TimeDiff year month day hour min sec _)
542 doFmt ('%':c:cs) = decode c ++ doFmt cs
543 doFmt (c:cs) = c : doFmt cs
547 'B' -> fst (months l !! fromEnum month)
548 'b' -> snd (months l !! fromEnum month)
549 'h' -> snd (months l !! fromEnum month)
550 'C' -> show2 (year `quot` 100)
551 'D' -> doFmt "%m/%d/%y"
555 'I' -> show2 (to12 hour)
557 'l' -> show2' (to12 hour)
559 'm' -> show2 (fromEnum month + 1)
561 'p' -> (if hour < 12 then fst else snd) (amPm l)
563 'r' -> doFmt (time12Fmt l)
564 'T' -> doFmt "%H:%M:%S"
567 's' -> show2 sec -- Implementation-dependent, sez the lib doc..
568 'X' -> doFmt (timeFmt l)
569 'x' -> doFmt (dateFmt l)
571 'y' -> show2 (year `rem` 100)
578 foreign import "libHS_cbits" "get_tm_sec" unsafe get_tm_sec :: MBytes -> IO Int
579 foreign import "libHS_cbits" "get_tm_min" unsafe get_tm_min :: MBytes -> IO Int
580 foreign import "libHS_cbits" "get_tm_hour" unsafe get_tm_hour :: MBytes -> IO Int
581 foreign import "libHS_cbits" "get_tm_mday" unsafe get_tm_mday :: MBytes -> IO Int
582 foreign import "libHS_cbits" "get_tm_mon" unsafe get_tm_mon :: MBytes -> IO Int
583 foreign import "libHS_cbits" "get_tm_year" unsafe get_tm_year :: MBytes -> IO Int
584 foreign import "libHS_cbits" "get_tm_wday" unsafe get_tm_wday :: MBytes -> IO Int
585 foreign import "libHS_cbits" "get_tm_yday" unsafe get_tm_yday :: MBytes -> IO Int
586 foreign import "libHS_cbits" "get_tm_isdst" unsafe get_tm_isdst :: MBytes -> IO Int
588 foreign import "libHS_cbits" "prim_ZONE" prim_ZONE :: Bytes -> IO Addr
589 foreign import "libHS_cbits" "prim_GMTOFF" prim_GMTOFF :: Bytes -> IO Int
591 foreign import "libHS_cbits" "sizeof_struct_tm" sizeof_struct_tm :: Int
594 -- believed to be at least 1 bit (the sign bit!) bigger than sizeof_time_t
599 type MBytes = MutableByteArray RealWorld Int
601 foreign import "libHS_cbits" "sizeof_time_t" sizeof_time_t :: Int
603 foreign import "libHS_cbits" "prim_SETZONE" unsafe prim_SETZONE :: MBytes -> MBytes -> IO Int
605 foreign import "libHS_cbits" "prim_toLocalTime" unsafe prim_toLocalTime :: Int64 -> MBytes -> IO Int
606 foreign import "libHS_cbits" "prim_toUTCTime" unsafe prim_toUTCTime :: Int64 -> MBytes -> IO Int
608 foreign import "libHS_cbits" "toLocalTime" unsafe prim_toLocalTime :: Int -> Bytes -> MBytes -> IO Int
609 foreign import "libHS_cbits" "toUTCTime" unsafe prim_toUTCTime :: Int -> Bytes -> MBytes -> IO Int
612 foreign import "libHS_cbits" "get_ZONE" unsafe get_ZONE :: MBytes -> IO Addr
613 foreign import "libHS_cbits" "GMTOFF" unsafe get_GMTOFF :: MBytes -> IO Int
616 foreign import "libHS_cbits" "toClockSec" unsafe
617 toClockSec :: Int -> Int -> Int -> Int -> Int
618 -> Int -> Int -> MBytes -> IO Int
620 foreign import "libHS_cbits" "getClockTime" unsafe
621 primGetClockTime :: MutableByteArray RealWorld Int
622 -> MutableByteArray RealWorld Int
624 foreign import "libHS_cbits" "showTime" unsafe