d6777ba7fd54ed1d8b7ccc1d67fd2f89f34b1687
[packages/time.git] / lib / Data / Time / LocalTime / Internal / CalendarDiffTime.hs
1 module Data.Time.LocalTime.Internal.CalendarDiffTime
2 (
3 -- * Calendar Duration
4 module Data.Time.LocalTime.Internal.CalendarDiffTime
5 ) where
6 #if MIN_VERSION_base(4,8,0)
7 #else
8 import Data.Monoid
9 #endif
10 #if MIN_VERSION_base(4,9,0)
11 import Data.Semigroup hiding (option)
12 #endif
13 import Data.Fixed
14 import Data.Time.Calendar.CalendarDiffDays
15 import Data.Time.Clock.Internal.NominalDiffTime
16
17 data CalendarDiffTime = CalendarDiffTime
18 { ctMonths :: Integer
19 , ctTime :: NominalDiffTime
20 } deriving (Eq)
21 #if MIN_VERSION_base(4,9,0)
22 -- | Additive
23 instance Semigroup CalendarDiffTime where
24 CalendarDiffTime m1 d1 <> CalendarDiffTime m2 d2 = CalendarDiffTime (m1 + m2) (d1 + d2)
25 #endif
26 -- | Additive
27 instance Monoid CalendarDiffTime where
28 mempty = CalendarDiffTime 0 0
29 #if MIN_VERSION_base(4,9,0)
30 mappend = (<>)
31 #else
32 mappend (CalendarDiffTime m1 d1) (CalendarDiffTime m2 d2) = CalendarDiffTime (m1 + m2) (d1 + d2)
33 #endif
34
35 instance Show CalendarDiffTime where
36 show (CalendarDiffTime m t) = "P" ++ show m ++ "MT" ++ showFixed True (realToFrac t :: Pico) ++ "S"
37
38 calendarTimeDays :: CalendarDiffDays -> CalendarDiffTime
39 calendarTimeDays (CalendarDiffDays m d) = CalendarDiffTime m $ fromInteger d * nominalDay
40
41 calendarTimeTime :: NominalDiffTime -> CalendarDiffTime
42 calendarTimeTime dt = CalendarDiffTime 0 dt
43
44 -- | Scale by a factor. Note that @scaleCalendarDiffTime (-1)@ will not perfectly invert a duration, due to variable month lengths.
45 scaleCalendarDiffTime :: Integer -> CalendarDiffTime -> CalendarDiffTime
46 scaleCalendarDiffTime k (CalendarDiffTime m d) = CalendarDiffTime (k * m) (fromInteger k * d)