7897e59c141e954d969b116435a89f8fa028d877
[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) && !MIN_VERSION_base(4,11,0)
11 import Data.Semigroup hiding (option)
12 #endif
13 import Data.Fixed
14 import Data.Typeable
15 import Data.Data
16 import Data.Time.Calendar.CalendarDiffDays
17 import Data.Time.Clock.Internal.NominalDiffTime
18
19 data CalendarDiffTime = CalendarDiffTime
20 { ctMonths :: Integer
21 , ctTime :: NominalDiffTime
22 } deriving (Eq,
23 Data
24 #if __GLASGOW_HASKELL__ >= 802
25 -- ^ @since 1.9.2
26 #endif
27 ,Typeable
28 #if __GLASGOW_HASKELL__ >= 802
29 -- ^ @since 1.9.2
30 #endif
31 )
32
33 #if MIN_VERSION_base(4,9,0)
34 -- | Additive
35 instance Semigroup CalendarDiffTime where
36 CalendarDiffTime m1 d1 <> CalendarDiffTime m2 d2 = CalendarDiffTime (m1 + m2) (d1 + d2)
37 #endif
38 -- | Additive
39 instance Monoid CalendarDiffTime where
40 mempty = CalendarDiffTime 0 0
41 #if MIN_VERSION_base(4,9,0)
42 mappend = (<>)
43 #else
44 mappend (CalendarDiffTime m1 d1) (CalendarDiffTime m2 d2) = CalendarDiffTime (m1 + m2) (d1 + d2)
45 #endif
46
47 instance Show CalendarDiffTime where
48 show (CalendarDiffTime m t) = "P" ++ show m ++ "MT" ++ showFixed True (realToFrac t :: Pico) ++ "S"
49
50 calendarTimeDays :: CalendarDiffDays -> CalendarDiffTime
51 calendarTimeDays (CalendarDiffDays m d) = CalendarDiffTime m $ fromInteger d * nominalDay
52
53 calendarTimeTime :: NominalDiffTime -> CalendarDiffTime
54 calendarTimeTime dt = CalendarDiffTime 0 dt
55
56 -- | Scale by a factor. Note that @scaleCalendarDiffTime (-1)@ will not perfectly invert a duration, due to variable month lengths.
57 scaleCalendarDiffTime :: Integer -> CalendarDiffTime -> CalendarDiffTime
58 scaleCalendarDiffTime k (CalendarDiffTime m d) = CalendarDiffTime (k * m) (fromInteger k * d)