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 Integer deriving (Eq, Ord)
90 When a @ClockTime@ is shown, it is converted to a string of the form
91 @"Mon Nov 28 21:45:41 GMT 1994"@.
93 For now, we are restricted to roughly:
94 Fri Dec 13 20:45:52 1901 through Tue Jan 19 03:14:07 2038, because
95 we use the C library routines based on 32 bit integers.
99 #warning Show ClockTime is bogus
100 instance Show ClockTime
102 instance Show ClockTime where
103 showsPrec p (TOD (S# i) _nsec) =
104 case int2Integer# i of (# s, d #) -> showsPrec p (TOD (J# s d) _nsec)
105 showsPrec _ (TOD (J# s# d#) _nsec) =
106 showString $ unsafePerformIO $ do
107 let buflen@(I# buflen#) = 50 -- big enough for error message
108 buf <- allocChars buflen
109 if s# <# (negateInt# 1#) || s# ># 1# then
110 return "ClockTime.show{Time}: out of range"
112 rc <- showTime (I# s#) d# buflen buf
114 return "ClockTime.show{Time}: internal error"
116 ba <- stToIO (freeze_ps_array buf buflen#)
117 return (unpackCStringBA ba)
119 showList = showList__ (showsPrec 0)
124 @CalendarTime@ is a user-readable and manipulable
125 representation of the internal $ClockTime$ type. The
126 numeric fields have the following ranges.
132 year -maxInt .. maxInt [Pre-Gregorian dates are inaccurate]
133 mon 0 .. 11 [Jan = 0, Dec = 11]
137 sec 0 .. 61 [Allows for two leap seconds]
138 picosec 0 .. (10^12)-1 [This could be over-precise?]
139 wday 0 .. 6 [Sunday = 0, Saturday = 6]
140 yday 0 .. 365 [364 in non-Leap years]
141 tz -43200 .. 43200 [Variation from UTC in seconds]
144 The {\em tzname} field is the name of the time zone. The {\em isdst}
145 field indicates whether Daylight Savings Time would be in effect.
159 ctPicosec :: Integer,
167 deriving (Eq,Ord,Read,Show)
171 The @TimeDiff@ type records the difference between two clock times in
184 tdPicosec :: Int64 -- not standard
186 tdPicosec :: Integer -- not standard
189 deriving (Eq,Ord,Read,Show)
191 noTimeDiff :: TimeDiff
192 noTimeDiff = TimeDiff 0 0 0 0 0 0 0
195 @getClockTime@ returns the current time in its internal representation.
198 getClockTime :: IO ClockTime
202 rc <- primGetClockTime i1 i2
205 sec <- cvtUnsigned i1
206 nsec <- cvtUnsigned i2
207 return (TOD sec (nsec * 1000))
209 constructErrorAndFail "getClockTime"
212 malloc1 = primNewByteArray sizeof_int64
213 cvtUnsigned arr = primReadInt64Array arr 0
215 malloc1 :: IO (MutableByteArray RealWorld Int)
216 malloc1 = IO $ \ s# ->
217 case newIntArray# 1# s# of
218 (# s2#, barr# #) -> (# s2#, MutableByteArray bot bot barr# #)
220 bot = error "Time.malloc1"
222 -- The C routine fills in an unsigned word. We don't have
223 -- `unsigned2Integer#,' so we freeze the data bits and use them
224 -- for an MP_INT structure. Note that zero is still handled specially,
225 -- although (J# 1# (ptr to 0#)) is probably acceptable to gmp.
227 cvtUnsigned :: MutableByteArray RealWorld Int -> IO Integer
228 cvtUnsigned (MutableByteArray _ _ arr#) = IO $ \ s# ->
229 case readIntArray# arr# 0# s# of
230 (# s2#, r# #) | r# ==# 0# -> (# s2#, 0 #)
232 case unsafeFreezeByteArray# arr# s2# of
233 (# s3#, frozen# #) -> (# s3#, J# 1# frozen# #)
237 @addToClockTime@ {\em d} {\em t} adds a time difference {\em d} and a
238 clock time {\em t} to yield a new clock time. The difference {\em d}
239 may be either positive or negative. @[diffClockTimes@ {\em t1} {\em
240 t2} returns the difference between two clock times {\em t1} and {\em
245 addToClockTime :: TimeDiff -> ClockTime -> ClockTime
246 addToClockTime (TimeDiff year mon day hour min sec psec)
249 sec_diff = fromInt sec + 60 * fromInt min + 3600 * fromInt hour + 24 * 3600 * fromInt day
250 cal = toUTCTime (TOD (c_sec + sec_diff) (c_psec + psec))
252 new_mon = fromEnum (ctMonth cal) + r_mon
254 | new_mon < 0 = (toEnum (12 + new_mon), (-1))
255 | new_mon > 11 = (toEnum (new_mon `mod` 12), 1)
256 | otherwise = (toEnum new_mon, 0)
258 (r_yr, r_mon) = mon `quotRem` 12
260 year' = ctYear cal + year + r_yr + yr_diff
262 toClockTime cal{ctMonth=month', ctYear=year'}
264 diffClockTimes :: ClockTime -> ClockTime -> TimeDiff
265 diffClockTimes tod_a tod_b =
267 CalendarTime year_a mon_a day_a hour_a min_a sec_a psec_a _ _ _ _ _ = toUTCTime tod_a
268 CalendarTime year_b mon_b day_b hour_b min_b sec_b psec_b _ _ _ _ _ = toUTCTime tod_b
270 TimeDiff (year_a - year_b)
271 (fromEnum mon_a - fromEnum mon_b)
279 @toCalendarTime@ {\em t} converts {\em t} to a local time, modified by
280 the current timezone and daylight savings time settings. @toUTCTime@
281 {\em t} converts {\em t} into UTC time. @toClockTime@ {\em l}
282 converts {\em l} into the corresponding internal @ClockTime@. The
283 {\em wday}, {\em yday}, {\em tzname}, and {\em isdst} fields are
288 toCalendarTime :: ClockTime -> IO CalendarTime
289 toCalendarTime (TOD sec psec) = do
290 res <- allocWords sizeof_int64
291 zoneNm <- allocChars 32
292 prim_SETZONE res zoneNm
293 rc <- prim_toLocalTime sec res
295 then constructErrorAndFail "Time.toCalendarTime: out of range"
297 sec <- get_tm_sec res
298 min <- get_tm_min res
299 hour <- get_tm_hour res
300 mday <- get_tm_mday res
301 mon <- get_tm_mon res
302 year <- get_tm_year res
303 wday <- get_tm_wday res
304 yday <- get_tm_yday res
305 isdst <- get_tm_isdst res
306 zone <- prim_ZONE res
307 tz <- prim_GMTOFF res
308 tzname <- primUnpackCString zone
309 return (CalendarTime (1900+year) mon mday hour min sec psec
310 (toEnum wday) yday tzname tz (isdst /= 0))
312 toUTCTime :: ClockTime -> CalendarTime
313 toUTCTime (TOD sec psec) = unsafePerformIO $ do
314 res <- allocWords sizeof_int64
315 zoneNm <- allocChars 32
316 prim_SETZONE res zoneNm
317 rc <- prim_toUTCTime sec res
319 then error "Time.toUTCTime: out of range"
321 sec <- get_tm_sec res
322 min <- get_tm_min res
323 hour <- get_tm_hour res
324 mday <- get_tm_mday res
325 mon <- get_tm_mon res
326 year <- get_tm_year res
327 wday <- get_tm_wday res
328 yday <- get_tm_yday res
329 return (CalendarTime (1900+year) mon mday hour min sec psec
330 (toEnum wday) yday "UTC" 0 False)
332 toClockTime :: CalendarTime -> ClockTime
333 toClockTime (CalendarTime year mon mday hour min sec psec wday yday tzname tz isdst) =
334 if psec < 0 || psec > 999999999999 then
335 error "Time.toClockTime: picoseconds out of range"
336 else if tz < -43200 || tz > 43200 then
337 error "Time.toClockTime: timezone offset out of range"
340 res <- allocWords sizeof_int64
341 rc <- toClockSec year (fromEnum mon) mday hour min sec isDst res
344 tm <- primReadInt64Array res 0
346 else error "Time.toClockTime: can't perform conversion"
349 isDst = if isdst then (1::Int) else 0
351 toCalendarTime :: ClockTime -> IO CalendarTime
352 toCalendarTime (TOD (S# i) psec)
353 = case int2Integer# i of (# s, d #) -> toCalendarTime (TOD (J# s d) psec)
354 toCalendarTime (TOD (J# s# d#) psec) = do
355 res <- allocWords sizeof_struct_tm
356 zoneNm <- allocChars 32
357 prim_SETZONE res zoneNm
358 rc <- prim_toLocalTime (I# s#) d# res
360 then constructErrorAndFail "Time.toCalendarTime: out of range"
362 sec <- get_tm_sec res
363 min <- get_tm_min res
364 hour <- get_tm_hour res
365 mday <- get_tm_mday res
366 mon <- get_tm_mon res
367 year <- get_tm_year res
368 wday <- get_tm_wday res
369 yday <- get_tm_yday res
370 isdst <- get_tm_isdst res
373 let tzname = unpackCString zone
375 | mon >= 0 && mon <= 11 = toEnum mon
376 | otherwise = error ("toCalendarTime: illegal month value: " ++ show mon)
378 return (CalendarTime (1900+year) month mday hour min sec psec
379 (toEnum wday) yday tzname tz (isdst /= (0::Int)))
381 toUTCTime :: ClockTime -> CalendarTime
382 toUTCTime (TOD (S# i) psec)
383 = case int2Integer# i of (# s, d #) -> toUTCTime (TOD (J# s d) psec)
384 toUTCTime (TOD (J# s# d#) psec) = unsafePerformIO $ do
385 res <- allocWords sizeof_struct_tm
386 zoneNm <- allocChars 32
387 prim_SETZONE res zoneNm
388 rc <- prim_toUTCTime (I# s#) d# res
390 then error "Time.toUTCTime: out of range"
392 sec <- get_tm_sec res
393 min <- get_tm_min res
394 hour <- get_tm_hour res
395 mday <- get_tm_mday res
396 mon <- get_tm_mon res
397 year <- get_tm_year res
398 wday <- get_tm_wday res
399 yday <- get_tm_yday res
402 | mon >= 0 && mon <= 11 = toEnum mon
403 | otherwise = error ("toCalendarTime: illegal month value: " ++ show mon)
405 return (CalendarTime (1900+year) month mday hour min sec psec
406 (toEnum wday) yday "UTC" 0 False)
408 toClockTime :: CalendarTime -> ClockTime
409 toClockTime (CalendarTime year mon mday hour min sec psec _wday _yday _tzname tz isdst) =
410 if psec < 0 || psec > 999999999999 then
411 error "Time.toClockTime: picoseconds out of range"
412 else if tz < -43200 || tz > 43200 then
413 error "Time.toClockTime: timezone offset out of range"
417 rc <- toClockSec year (fromEnum mon) mday hour min sec isDst res
422 else error "Time.toClockTime: can't perform conversion"
425 isDst = if isdst then (1::Int) else 0
429 -- (copied from PosixUtil, for now)
430 -- Allocate a mutable array of characters with no indices.
433 allocChars :: Int -> IO (PrimMutableByteArray RealWorld)
434 allocChars size = primNewByteArray size
436 -- Allocate a mutable array of words with no indices
438 allocWords :: Int -> IO (PrimMutableByteArray RealWorld)
439 allocWords size = primNewByteArray size
441 allocChars :: Int -> IO (MutableByteArray RealWorld Int)
442 allocChars (I# size#) = stToIO (new_ps_array size#)
444 -- Allocate a mutable array of words with no indices
446 allocWords :: Int -> IO (MutableByteArray RealWorld Int)
447 allocWords (I# size#) = IO $ \ s# ->
448 case newIntArray# size# s# of
450 (# s2#, MutableByteArray bot bot barr# #)
452 bot = error "Time.allocWords"
457 calendarTimeToString :: CalendarTime -> String
458 calendarTimeToString = formatCalendarTime defaultTimeLocale "%c"
460 formatCalendarTime :: TimeLocale -> String -> CalendarTime -> String
461 formatCalendarTime l fmt (CalendarTime year mon day hour min sec _
462 wday yday tzname _ _) =
464 where doFmt ('%':c:cs) = decode c ++ doFmt cs
465 doFmt (c:cs) = c : doFmt cs
468 decode 'A' = fst (wDays l !! fromEnum wday) -- day of the week, full name
469 decode 'a' = snd (wDays l !! fromEnum wday) -- day of the week, abbrev.
470 decode 'B' = fst (months l !! fromEnum mon) -- month, full name
471 decode 'b' = snd (months l !! fromEnum mon) -- month, abbrev
472 decode 'h' = snd (months l !! fromEnum mon) -- ditto
473 decode 'C' = show2 (year `quot` 100) -- century
474 decode 'c' = doFmt (dateTimeFmt l) -- locale's data and time format.
475 decode 'D' = doFmt "%m/%d/%y"
476 decode 'd' = show2 day -- day of the month
477 decode 'e' = show2' day -- ditto, padded
478 decode 'H' = show2 hour -- hours, 24-hour clock, padded
479 decode 'I' = show2 (to12 hour) -- hours, 12-hour clock
480 decode 'j' = show3 yday -- day of the year
481 decode 'k' = show2' hour -- hours, 24-hour clock, no padding
482 decode 'l' = show2' (to12 hour) -- hours, 12-hour clock, no padding
483 decode 'M' = show2 min -- minutes
484 decode 'm' = show2 (fromEnum mon+1) -- numeric month
486 decode 'p' = (if hour < 12 then fst else snd) (amPm l) -- am or pm
487 decode 'R' = doFmt "%H:%M"
488 decode 'r' = doFmt (time12Fmt l)
489 decode 'T' = doFmt "%H:%M:%S"
491 decode 'S' = show2 sec -- seconds
492 decode 's' = show2 sec -- number of secs since Epoch. (ToDo.)
493 decode 'U' = show2 ((yday + 7 - fromEnum wday) `div` 7) -- week number, starting on Sunday.
494 decode 'u' = show (let n = fromEnum wday in -- numeric day of the week (1=Monday, 7=Sunday)
495 if n == 0 then 7 else n)
496 decode 'V' = -- week number (as per ISO-8601.)
497 let (week, days) = -- [yep, I've always wanted to be able to display that too.]
498 (yday + 7 - if fromEnum wday > 0 then
499 fromEnum wday - 1 else 6) `divMod` 7
500 in show2 (if days >= 4 then
502 else if week == 0 then 53 else week)
504 decode 'W' = -- week number, weeks starting on monday
505 show2 ((yday + 7 - if fromEnum wday > 0 then
506 fromEnum wday - 1 else 6) `div` 7)
507 decode 'w' = show (fromEnum wday) -- numeric day of the week, weeks starting on Sunday.
508 decode 'X' = doFmt (timeFmt l) -- locale's preferred way of printing time.
509 decode 'x' = doFmt (dateFmt l) -- locale's preferred way of printing dates.
510 decode 'Y' = show year -- year, including century.
511 decode 'y' = show2 (year `rem` 100) -- year, within century.
512 decode 'Z' = tzname -- timezone name
517 show2, show2', show3 :: Int -> String
518 show2 x = [intToDigit (x `quot` 10), intToDigit (x `rem` 10)]
520 show2' x = if x < 10 then [ ' ', intToDigit x] else show2 x
522 show3 x = intToDigit (x `quot` 100) : show2 (x `rem` 100)
525 to12 h = let h' = h `mod` 12 in if h' == 0 then 12 else h'
528 Useful extensions for formatting TimeDiffs.
531 timeDiffToString :: TimeDiff -> String
532 timeDiffToString = formatTimeDiff defaultTimeLocale "%c"
534 formatTimeDiff :: TimeLocale -> String -> TimeDiff -> String
535 formatTimeDiff l fmt (TimeDiff year month day hour min sec _)
539 doFmt ('%':c:cs) = decode c ++ doFmt cs
540 doFmt (c:cs) = c : doFmt cs
544 'B' -> fst (months l !! fromEnum month)
545 'b' -> snd (months l !! fromEnum month)
546 'h' -> snd (months l !! fromEnum month)
547 'C' -> show2 (year `quot` 100)
548 'D' -> doFmt "%m/%d/%y"
552 'I' -> show2 (to12 hour)
554 'l' -> show2' (to12 hour)
556 'm' -> show2 (fromEnum month + 1)
558 'p' -> (if hour < 12 then fst else snd) (amPm l)
560 'r' -> doFmt (time12Fmt l)
561 'T' -> doFmt "%H:%M:%S"
564 's' -> show2 sec -- Implementation-dependent, sez the lib doc..
565 'X' -> doFmt (timeFmt l)
566 'x' -> doFmt (dateFmt l)
568 'y' -> show2 (year `rem` 100)
575 foreign import "libHS_cbits" "get_tm_sec" unsafe get_tm_sec :: MBytes -> IO Int
576 foreign import "libHS_cbits" "get_tm_min" unsafe get_tm_min :: MBytes -> IO Int
577 foreign import "libHS_cbits" "get_tm_hour" unsafe get_tm_hour :: MBytes -> IO Int
578 foreign import "libHS_cbits" "get_tm_mday" unsafe get_tm_mday :: MBytes -> IO Int
579 foreign import "libHS_cbits" "get_tm_mon" unsafe get_tm_mon :: MBytes -> IO Int
580 foreign import "libHS_cbits" "get_tm_year" unsafe get_tm_year :: MBytes -> IO Int
581 foreign import "libHS_cbits" "get_tm_wday" unsafe get_tm_wday :: MBytes -> IO Int
582 foreign import "libHS_cbits" "get_tm_yday" unsafe get_tm_yday :: MBytes -> IO Int
583 foreign import "libHS_cbits" "get_tm_isdst" unsafe get_tm_isdst :: MBytes -> IO Int
585 foreign import "libHS_cbits" "prim_ZONE" prim_ZONE :: Bytes -> IO Addr
586 foreign import "libHS_cbits" "prim_GMTOFF" prim_GMTOFF :: Bytes -> IO Int
588 foreign import "libHS_cbits" "sizeof_struct_tm" sizeof_struct_tm :: Int
591 -- believed to be at least 1 bit (the sign bit!) bigger than sizeof_time_t
596 type MBytes = MutableByteArray RealWorld Int
598 foreign import "libHS_cbits" "sizeof_time_t" sizeof_time_t :: Int
600 foreign import "libHS_cbits" "prim_SETZONE" unsafe prim_SETZONE :: MBytes -> MBytes -> IO Int
602 foreign import "libHS_cbits" "prim_toLocalTime" unsafe prim_toLocalTime :: Int64 -> MBytes -> IO Int
603 foreign import "libHS_cbits" "prim_toUTCTime" unsafe prim_toUTCTime :: Int64 -> MBytes -> IO Int
605 foreign import "libHS_cbits" "toLocalTime" unsafe prim_toLocalTime :: Int -> Bytes -> MBytes -> IO Int
606 foreign import "libHS_cbits" "toUTCTime" unsafe prim_toUTCTime :: Int -> Bytes -> MBytes -> IO Int
609 foreign import "libHS_cbits" "get_ZONE" unsafe get_ZONE :: MBytes -> IO Addr
610 foreign import "libHS_cbits" "GMTOFF" unsafe get_GMTOFF :: MBytes -> IO Int
613 foreign import "libHS_cbits" "toClockSec" unsafe
614 toClockSec :: Int -> Int -> Int -> Int -> Int
615 -> Int -> Int -> MBytes -> IO Int
617 foreign import "libHS_cbits" "getClockTime" unsafe
618 primGetClockTime :: MutableByteArray RealWorld Int
619 -> MutableByteArray RealWorld Int
621 foreign import "libHS_cbits" "showTime" unsafe