How to get the start time of the previous month in Haskell?

Viewed 88

I'd like to get the "start" time (the time right at the beginning of the month), of the previous month relative to the current time.

How can I do this?

1 Answers

Using UTCTime we can define a function:

import Data.Time

getStartOfPreviousMonth :: UTCTime -> UTCTime 
getStartOfPreviousMonth v = do
  let (y,m,_) = (toGregorian $ utctDay v)
  let v' = addGregorianMonthsClip (-1) $ fromGregorian y m 1
  v { utctDay = v'
    , utctDayTime = secondsToDiffTime 0
    }

Which can be used like so:

> import Data.Time
Data.Time> ct <- getCurrentTime
Data.Time> getStartOfPreviousMonth ct
2020-07-01 00:00:00 UTC
Related