hledger-lib-1.52.1: A library providing the core functionality of hledger

Safe Haskell | None
Language | GHC2021

Hledger.Data.Dates

Contents

- Misc date handling utilities
- Orphan instances

Description

Date parsing and utilities for hledger.

For date and time values, we use the standard Day and UTCTime types.

A `SmartDate` is a date which may be partially-specified or relative. Eg 2008/12/31, but also 2008/12, 12/31, tomorrow, last week, next year, in 5 days, in -3 quarters. We represent these as a triple of strings like ("2008","12",""), ("","","tomorrow"), ("","last","week").

A `DateSpan` is the span of time between two specific calendar dates, or an open-ended span where one or both dates are unspecified. (A date span with both ends unspecified matches all dates.)

An `Interval` is ledger's "reporting interval" - weekly, monthly, quarterly, etc.

`Period` will probably replace DateSpan in due course.

Synopsis

- fromEFDay :: EFDay -> Day
- modifyEFDay :: (Day -> Day) -> EFDay -> EFDay
- getCurrentDay :: IO Day
- getCurrentMonth :: IO Int
- getCurrentYear :: IO Integer
- nulldate :: Day
- spanContainsDate :: DateSpan -> Day -> Bool
- periodContainsDate :: Period -> Day -> Bool
- parsedate :: String -> Maybe Day
- showDate :: Day -> Text
- showEFDate :: EFDay -> Text
- showDateSpan :: DateSpan -> Text
- showDateSpanDebug :: DateSpan -> String
- showDateSpanAbbrev :: DateSpan -> Text
- elapsedSeconds :: Fractional a => UTCTime -> UTCTime -> a
- prevday :: Day -> Day
- periodexprp :: forall (m :: Type -> Type). Day -> TextParser m (Interval, DateSpan)
- parsePeriodExpr :: Day -> Text -> Either HledgerParseErrors (Interval, DateSpan)
- parsePeriodExpr' :: Day -> Text -> (Interval, DateSpan)
- nulldatespan :: DateSpan
- emptydatespan :: DateSpan
- datesepchar :: forall (m :: Type -> Type). TextParser m Char
- datesepchars :: String
- isDateSepChar :: Char -> Bool
- spanStart :: DateSpan -> Maybe Day
- spanEnd :: DateSpan -> Maybe Day
- spanStartYear :: DateSpan -> Maybe Year
- spanEndYear :: DateSpan -> Maybe Year
- spanYears :: DateSpan -> [Year]
- spansSpan :: [DateSpan] -> DateSpan
- spanIntersect :: DateSpan -> DateSpan -> DateSpan
- spansIntersect :: [DateSpan] -> DateSpan
- spanDefaultsFrom :: DateSpan -> DateSpan -> DateSpan
- spanValidDefaultsFrom :: DateSpan -> DateSpan -> DateSpan
- spanExtend :: DateSpan -> DateSpan -> DateSpan
- spanUnion :: DateSpan -> DateSpan -> DateSpan
- spansUnion :: [DateSpan] -> DateSpan
- daysSpan :: [Day] -> DateSpan
- latestSpanContaining :: [DateSpan] -> Day -> Maybe DateSpan
- smartdate :: forall (m :: Type -> Type). TextParser m SmartDate
- groupByDateSpan :: Bool -> (a -> Day) -> [DateSpan] -> [a] -> [(DateSpan, [a])]
- fixSmartDate :: Day -> SmartDate -> EFDay
- fixSmartDateStr :: Day -> Text -> Text
- fixSmartDateStrEither :: Day -> Text -> Either HledgerParseErrors Text
- fixSmartDateStrEither' :: Day -> Text -> Either HledgerParseErrors EFDay
- yearp :: forall (m :: Type -> Type). TextParser m Integer
- daysInSpan :: DateSpan -> Maybe Integer
- startofyear :: Day -> Day
- startofquarter :: Day -> Day
- startofmonth :: Day -> Day
- startofweek :: Day -> Day
- nextday :: Day -> Day
- nextweek :: Day -> Day
- nextmonthandday :: Month -> MonthDay -> Day -> Day
- nextnthdayofmonth :: MonthDay -> Day -> Day
- prevNthWeekdayOfMonth :: Int -> WeekDay -> Day -> Day
- nthdayofweekcontaining :: WeekDay -> Day -> Day
- addGregorianMonthsToMonthday :: MonthDay -> Integer -> Day -> Day
- advanceToNthWeekday :: Int -> WeekDay -> Day -> Day
- nextNthWeekdayOfMonth :: Int -> WeekDay -> Day -> Day
- isEmptySpan :: DateSpan -> Bool

# Misc date handling utilities

fromEFDay :: EFDay -> Day Source #

modifyEFDay :: (Day -> Day) -> EFDay -> EFDay Source #

getCurrentDay :: IO Day Source #

Get the current local date.

getCurrentMonth :: IO Int Source #

Get the current local month number.

getCurrentYear :: IO Integer Source #

Get the current local year.

nulldate :: Day Source #

spanContainsDate :: DateSpan -> Day -> Bool Source #

Does the span include the given date ?

periodContainsDate :: Period -> Day -> Bool Source #

Does the period include the given date ? (Here to avoid import cycle).

parsedate :: String -> Maybe Day Source #

A simple date parsing helper: parses these YMD date string formats: `YYYY-MM-DD`, `YYYYMMDD`, `DD` or `YYYYMMDD`, where the month and day each have two digits and the year has one or more.

This is different from the Smart Dates of the CLI and period expressions ("smartdate", below) and not quite the same as the Simple Dates of the journal ("datep", in Hledger.Read.Common). It's mainly for internal or interactive use, eg when debugging - but currently is also used in a few user-facing places, such as: parsing --value's argument, parsing .latest files, and parsing hledger's --version output (which uses unseparated dates).

Unseparated dates were added in 2025 for convenience. Note it means many integers will now parse successfully.

    >>> parsedate "2008/02/03"
    Just 2008-02-03
    >>> parsedate "2008/02/03/"
    Nothing
    >>> parsedate "2008/02/30"
    Nothing
    >>> parsedate "2025-01-01"
    Just 2025-01-01
    >>> parsedate "2025.01.01"
    Just 2025-01-01
    >>> parsedate "20250101"
    Just 2025-01-01
    >>> parsedate "00101"
    Just 0000-01-01

showDate :: Day -> Text Source #

showEFDate :: EFDay -> Text Source #

showDateSpan :: DateSpan -> Text Source #

Render a datespan as a display string, abbreviating into a compact form if possible. Warning, hides whether dates are Exact or Flex.

showDateSpanDebug :: DateSpan -> String Source #

Show a DateSpan with its begin/end dates, exact or flex.

showDateSpanAbbrev :: DateSpan -> Text Source #

Like showDateSpan, but show month spans as just the abbreviated month name in the current locale.

elapsedSeconds :: Fractional a => UTCTime -> UTCTime -> a Source #

prevday :: Day -> Day Source #

periodexprp :: forall (m :: Type -> Type). Day -> TextParser m (Interval, DateSpan) Source #

Parse a period expression, specifying a date span and optionally a reporting interval. Requires a reference "today" date for resolving any relative start/end dates (only; it is not needed for parsing the reporting interval).

    >>> let p = parsePeriodExpr (fromGregorian 2008 11 26)
    >>> p "from Aug to Oct"
    Right (NoInterval,DateSpan 2008-08-01..2008-09-30)
    >>> p "aug to oct"
    Right (NoInterval,DateSpan 2008-08-01..2008-09-30)
    >>> p "2009q2"
    Right (NoInterval,DateSpan 2009Q2)
    >>> p "Q3"
    Right (NoInterval,DateSpan 2008Q3)
    >>> p "every 3 days in Aug"
    Right (Days 3,DateSpan 2008-08)
    >>> p "daily from aug"
    Right (Days 1,DateSpan 2008-08-01..)
    >>> p "every week to 2009"
    Right (Weeks 1,DateSpan ..2008-12-31)
    >>> p "every 2nd day of month"
    Right (MonthDay 2,DateSpan ..)
    >>> p "every 2nd day"
    Right (MonthDay 2,DateSpan ..)
    >>> p "every 2nd day 2009.."
    Right (MonthDay 2,DateSpan 2009-01-01..)
    >>> p "every 2nd day 2009-"
    Right (MonthDay 2,DateSpan 2009-01-01..)
    >>> p "every 29th Nov"
    Right (MonthAndDay 11 29,DateSpan ..)
    >>> p "every 29th nov ..2009"
    Right (MonthAndDay 11 29,DateSpan ..2008-12-31)
    >>> p "every nov 29th"
    Right (MonthAndDay 11 29,DateSpan ..)
    >>> p "every Nov 29th 2009.."
    Right (MonthAndDay 11 29,DateSpan 2009-01-01..)
    >>> p "every 11/29 from 2009"
    Right (MonthAndDay 11 29,DateSpan 2009-01-01..)
    >>> p "every 11/29 since 2009"
    Right (MonthAndDay 11 29,DateSpan 2009-01-01..)
    >>> p "every 2nd Thursday of month to 2009"
    Right (NthWeekdayOfMonth 2 4,DateSpan ..2008-12-31)
    >>> p "every 1st monday of month to 2009"
    Right (NthWeekdayOfMonth 1 1,DateSpan ..2008-12-31)
    >>> p "every tue"
    Right (DaysOfWeek [2],DateSpan ..)
    >>> p "every 2nd day of week"
    Right (DaysOfWeek [2],DateSpan ..)
    >>> p "every 2nd day of month"
    Right (MonthDay 2,DateSpan ..)
    >>> p "every 2nd day"
    Right (MonthDay 2,DateSpan ..)
    >>> p "every 2nd day 2009.."
    Right (MonthDay 2,DateSpan 2009-01-01..)
    >>> p "every 2nd day of month 2009.."
    Right (MonthDay 2,DateSpan 2009-01-01..)

parsePeriodExpr :: Day -> Text -> Either HledgerParseErrors (Interval, DateSpan) Source #

Parse a period expression to an Interval and overall DateSpan using the provided reference date, or return a parse error.

parsePeriodExpr' :: Day -> Text -> (Interval, DateSpan) Source #

Like parsePeriodExpr, but call error' on failure.

nulldatespan :: DateSpan Source #

emptydatespan :: DateSpan Source #

An exact datespan of zero length, that matches no date.

datesepchar :: forall (m :: Type -> Type). TextParser m Char Source #

datesepchars :: String Source #

isDateSepChar :: Char -> Bool Source #

spanStart :: DateSpan -> Maybe Day Source #

spanEnd :: DateSpan -> Maybe Day Source #

spanStartYear :: DateSpan -> Maybe Year Source #

spanEndYear :: DateSpan -> Maybe Year Source #

spanYears :: DateSpan -> [Year] Source #

Get the 0-2 years mentioned explicitly in a DateSpan.

spansSpan :: [DateSpan] -> DateSpan Source #

Get overall span enclosing multiple sequentially ordered spans. The start and end date will be exact or flexible depending on the first span's start date and last span's end date.

spanIntersect :: DateSpan -> DateSpan -> DateSpan Source #

Calculate the intersection of two datespans.

For non-intersecting spans, gives an empty span beginning on the second's start date: >>> DateSpan (Just $ Flex $ fromGregorian 2018 01 01) (Just $ Flex $ fromGregorian 2018 01 03) `spanIntersect` DateSpan (Just $ Flex $ fromGregorian 2018 01 03) (Just $ Flex $ fromGregorian 2018 01 05) DateSpan 2018-01-03..2018-01-02

spansIntersect :: [DateSpan] -> DateSpan Source #

Calculate the intersection of a number of datespans.

spanDefaultsFrom :: DateSpan -> DateSpan -> DateSpan Source #

Fill any unspecified dates in the first span with the dates from the second one (if specified there). Sort of a one-way spanIntersect. This one can create an invalid span that'll always be empty.

    >>> :{
     DateSpan (Just $ Exact $ fromGregorian 2024 1 1) Nothing
     `spanDefaultsFrom`
     DateSpan (Just $ Exact $ fromGregorian 2024 1 1) (Just $ Exact $ fromGregorian 2024 1 2)
    :}
    DateSpan 2024-01-01

    >>> :{
     DateSpan (Just $ Exact $ fromGregorian 2025 1 1) Nothing
     `spanDefaultsFrom`
     DateSpan (Just $ Exact $ fromGregorian 2024 1 1) (Just $ Exact $ fromGregorian 2024 1 2)
    :}
    DateSpan 2025-01-01..2024-01-01

spanValidDefaultsFrom :: DateSpan -> DateSpan -> DateSpan Source #

A smarter version of spanDefaultsFrom that avoids creating invalid spans ending before they begin. Kept separate for now to reduce risk.

    >>> :{
     DateSpan (Just $ Exact $ fromGregorian 2025 1 1) Nothing
     `spanValidDefaultsFrom`
     DateSpan (Just $ Exact $ fromGregorian 2024 1 1) (Just $ Exact $ fromGregorian 2024 1 2)
    :}
    DateSpan 2025-01-01..

spanExtend :: DateSpan -> DateSpan -> DateSpan Source #

Extend the definite start/end dates of the first span, if needed, to include the definite start/end dates of the second span. Andor, replace open startend dates in the first span with definite start/end dates from the second. Unlike spanUnion, open start/end dates in the second are ignored.

    >>> ys2024 = fromGregorian 2024 01 01
    >>> ys2025 = fromGregorian 2025 01 01
    >>> to2024 = DateSpan Nothing               (Just $ Exact ys2024)
    >>> all2024 = DateSpan (Just $ Exact ys2024) (Just $ Exact ys2025)
    >>> partof2024 = DateSpan (Just $ Exact $ fromGregorian 2024 03 01) (Just $ Exact $ fromGregorian 2024 09 01)
    >>> spanExtend to2024 all2024
    DateSpan 2024
    >>> spanExtend all2024 to2024
    DateSpan 2024
    >>> spanExtend partof2024 all2024
    DateSpan 2024
    >>> spanExtend all2024 partof2024
    DateSpan 2024

spanUnion :: DateSpan -> DateSpan -> DateSpan Source #

Calculate the union of two datespans. If either span is open-ended, the union will be too.

    >>> ys2024 = fromGregorian 2024 01 01
    >>> ys2025 = fromGregorian 2025 01 01
    >>> to2024 = DateSpan Nothing               (Just $ Exact ys2024)
    >>> in2024 = DateSpan (Just $ Exact ys2024) (Just $ Exact ys2025)
    >>> spanUnion to2024 in2024
    DateSpan ..2024-12-31
    >>> spanUnion in2024 to2024
    DateSpan ..2024-12-31

spansUnion :: [DateSpan] -> DateSpan Source #

Calculate the union of a number of datespans.

daysSpan :: [Day] -> DateSpan Source #

Calculate the minimal DateSpan containing all of the given Days (in the usual exclusive-end-date sense: beginning on the earliest, and ending on the day after the latest).

latestSpanContaining :: [DateSpan] -> Day -> Maybe DateSpan Source #

Select the DateSpan containing a given Day, if any, from a given list of DateSpans.

If the DateSpans are non-overlapping, this returns the unique containing DateSpan, if it exists. If the DateSpans are overlapping, it will return the containing DateSpan with the latest start date, and then latest end date.

smartdate :: forall (m :: Type -> Type). TextParser m SmartDate Source #

Parse a date in any of the formats allowed in Ledger's period expressions, and some others. Assumes any text in the parse stream has been lowercased. Returns a SmartDate, to be converted to a full date later (see fixSmartDate).

Examples:

    2004                                        (start of year, which must have 4+ digits)
    2004/10                                     (start of month, which must be 1-12)
    2004/10/1                                   (exact date, day must be 1-31)
    10/1                                        (month and day in current year)
    21                                          (day in current month)
    october, oct                                (start of month in current year)
    yesterday, today, tomorrow                  (-1, 0, 1 days from today)
    last/this/next day/week/month/quarter/year  (-1, 0, 1 periods from the current period)
    last/this/next monday/mon                   (the previous or next named weekday; this=next)
    last/next january/jan                       (previous or next start of named month; this disallowed to avoid confusion)
    in n days/weeks/months/quarters/years       (n periods from the current period)
    n days/weeks/months/quarters/years ago      (-n periods from the current period)
    20181201                                    (8 digit YYYYMMDD with valid year month and day)
    201812                                      (6 digit YYYYMM with valid year and month)

Note malformed digit sequences might give surprising results:

    201813                                      (6 digits with an invalid month is parsed as start of 6-digit year)
    20181301                                    (8 digits with an invalid month is parsed as start of 8-digit year)
    20181232                                    (8 digits with an invalid day gives an error)
    201801012                                   (9+ digits beginning with a valid YYYYMMDD gives an error)

Eg:

YYYYMMDD is parsed as year-month-date if those parts are valid (>=4 digits, 1-12, and 1-31 respectively): >>> parsewith (smartdate <* eof) "20181201" Right (SmartCompleteDate 2018-12-01)

YYYYMM is parsed as year-month-01 if year and month are valid: >>> parsewith (smartdate <* eof) "201804" Right (SmartAssumeStart 2018 (Just 4))

With an invalid month, it's parsed as a year: >>> parsewith (smartdate <* eof) "201813" Right (SmartAssumeStart 201813 Nothing)

A 9+ digit number beginning with valid YYYYMMDD gives an error: >>> parsewith (smartdate <* eof) "201801012" Left (...)

Big numbers not beginning with a valid YYYYMMDD are parsed as a year: >>> parsewith (smartdate <* eof) "201813012" Right (SmartAssumeStart 201813012 Nothing)

groupByDateSpan :: Bool -> (a -> Day) -> [DateSpan] -> [a] -> [(DateSpan, [a])] Source #

Group elements based on where they fall in a list of `DateSpan`s without gaps. The precondition is not checked.

fixSmartDate :: Day -> SmartDate -> EFDay Source #

Convert a SmartDate to a specific date using the provided reference date. This date will be exact or flexible depending on whether the day was specified exactly. (Missing least-significant parts produces a flex date.)

#### Examples:

    >>> :set -XOverloadedStrings
    >>> let t = fixSmartDateStr (fromGregorian 2008 11 26)
    >>> t "0000-01-01"
    "0000-01-01"
    >>> t "1999-12-02"
    "1999-12-02"
    >>> t "1999.12.02"
    "1999-12-02"
    >>> t "1999/3/2"
    "1999-03-02"
    >>> t "19990302"
    "1999-03-02"
    >>> t "2008/2"
    "2008-02-01"
    >>> t "0020/2"
    "0020-02-01"
    >>> t "1000"
    "1000-01-01"
    >>> t "4/2"
    "2008-04-02"
    >>> t "2"
    "2008-11-02"
    >>> t "January"
    "2008-01-01"
    >>> t "feb"
    "2008-02-01"
    >>> t "today"
    "2008-11-26"
    >>> t "yesterday"
    "2008-11-25"
    >>> t "tomorrow"
    "2008-11-27"
    >>> t "this day"
    "2008-11-26"
    >>> t "last day"
    "2008-11-25"
    >>> t "next day"
    "2008-11-27"
    >>> t "this week"  -- last monday
    "2008-11-24"
    >>> t "last week"  -- previous monday
    "2008-11-17"
    >>> t "next week"  -- next monday
    "2008-12-01"
    >>> t "this month"
    "2008-11-01"
    >>> t "last month"
    "2008-10-01"
    >>> t "next month"
    "2008-12-01"
    >>> t "this quarter"
    "2008-10-01"
    >>> t "last quarter"
    "2008-07-01"
    >>> t "next quarter"
    "2009-01-01"
    >>> t "this year"
    "2008-01-01"
    >>> t "last year"
    "2007-01-01"
    >>> t "next year"
    "2009-01-01"

refdate is Wednesday, 2008-11-26 >>> t "last wednesday" "2008-11-19" >>> t "this wednesday" "2008-12-03" >>> t "next wednesday" "2008-12-03" >>> t "last january" "2008-01-01" >>> t "this january" "2009-01-01" >>> t "next january" "2009-01-01" >>> t "last november" "2007-11-01" >>> t "this november" "2009-11-01" >>> t "next november" "2009-11-01"

    >>> t "in 5 days"
    "2008-12-01"
    >>> t "in 7 months"
    "2009-06-01"
    >>> t "in -2 weeks"
    "2008-11-10"
    >>> t "1 quarter ago"
    "2008-07-01"
    >>> t "1 week ahead"
    "2008-12-01"

fixSmartDateStr :: Day -> Text -> Text Source #

Convert a smart date string to an explicit yyyy/mm/dd string using the provided reference date, or raise an error.

fixSmartDateStrEither :: Day -> Text -> Either HledgerParseErrors Text Source #

A safe version of fixSmartDateStr.

fixSmartDateStrEither' :: Day -> Text -> Either HledgerParseErrors EFDay Source #

yearp :: forall (m :: Type -> Type). TextParser m Integer Source #

Parse a year number from a Text, making sure that at least four digits are used.

daysInSpan :: DateSpan -> Maybe Integer Source #

Count the days in a DateSpan, or if it is open-ended return Nothing.

startofyear :: Day -> Day Source #

startofquarter :: Day -> Day Source #

startofmonth :: Day -> Day Source #

startofweek :: Day -> Day Source #

nextday :: Day -> Day Source #

nextweek :: Day -> Day Source #

nextmonthandday :: Month -> MonthDay -> Day -> Day Source #

Find the next occurrence of the specified month and day of month, on or after the given date. The month should be 1-12 and the day of month should be 1-31, or an error will be raised.

    >>> let wed22nd = fromGregorian 2017 11 22
    >>> nextmonthandday 11 21 wed22nd
    2018-11-21
    >>> nextmonthandday 11 22 wed22nd
    2017-11-22
    >>> nextmonthandday 11 23 wed22nd
    2017-11-23

nextnthdayofmonth :: MonthDay -> Day -> Day Source #

Find the next occurrence of the specified day of month, on or after the given date. The day of month should be 1-31, or an error will be raised.

    >>> let wed22nd = fromGregorian 2017 11 22
    >>> nextnthdayofmonth 21 wed22nd
    2017-12-21
    >>> nextnthdayofmonth 22 wed22nd
    2017-11-22
    >>> nextnthdayofmonth 23 wed22nd
    2017-11-23

prevNthWeekdayOfMonth :: Int -> WeekDay -> Day -> Day Source #

Find the previous occurrence of some nth weekday of a month, on or before the given date d.

    >>> let wed22nd = fromGregorian 2017 11 22
    >>> prevNthWeekdayOfMonth 4 3 wed22nd
    2017-11-22
    >>> prevNthWeekdayOfMonth 5 2 wed22nd
    2017-10-31

nthdayofweekcontaining :: WeekDay -> Day -> Day Source #

For given date d find week-long interval that starts on nth day of week and covers it.

Examples: 2017-11-22 is Wed. Week-long intervals that cover it and start on Mon, Tue or Wed will start in the same week. However intervals that start on Thu or Fri should start in prev week: >>> let wed22nd = fromGregorian 2017 11 22 >>> nthdayofweekcontaining 1 wed22nd 2017-11-20 >>> nthdayofweekcontaining 2 wed22nd 2017-11-21 >>> nthdayofweekcontaining 3 wed22nd 2017-11-22 >>> nthdayofweekcontaining 4 wed22nd 2017-11-16 >>> nthdayofweekcontaining 5 wed22nd 2017-11-17

addGregorianMonthsToMonthday :: MonthDay -> Integer -> Day -> Day Source #

advanceToNthWeekday :: Int -> WeekDay -> Day -> Day Source #

Advance to the nth occurrence of the given weekday, on or after the given date. Can call error.

nextNthWeekdayOfMonth :: Int -> WeekDay -> Day -> Day Source #

Find the next occurrence of some nth weekday of a month, on or after the given date d.

    >>> let wed22nd = fromGregorian 2017 11 22
    >>> nextNthWeekdayOfMonth 3 3 wed22nd  -- next third wednesday
    2017-12-20
    >>> nextNthWeekdayOfMonth 4 3 wed22nd  -- next fourth wednesday
    2017-11-22
    >>> nextNthWeekdayOfMonth 5 3 wed22nd  -- next fifth wednesday
    2017-11-29

isEmptySpan :: DateSpan -> Bool Source #

Is this an empty span, ie closed with the end date on or before the start date ?

# Orphan instances

Show DateSpan Source # |
Instance details Methods showsPrec :: Int -> DateSpan -> ShowS Source # show :: DateSpan -> String Source # showList :: [DateSpan] -> ShowS Source #