Dates between today and another date

I am burning my brains out trying to make a function that gives me the number of days between today's date and a specific date.

opportunity today :

today = fmap (formatTime defaultTimeLocale "%Y-%m-%d") getCurrentTime

      

and thought using diffDays

but can't get it to work with date :: Day

any ideas?

+3


source to share


1 answer


Your version formatTime

returns a string, but you want Day

(which looks like your string when you check it, but a completely different type). Here's one way to write a function today

using utctDay

to get Day

from UTCTime

:

import Data.Time.Calendar
import Data.Time.Clock

today :: IO Day
today = fmap utctDay getCurrentTime

      

And here's the days-from-today function (which I gave the shorter name daysAway

) that uses it:

daysAway :: Day -> IO Integer
daysAway day = fmap (diffDays day) today

      

If you always specify the goal as a calendar date, you can do it quite easily:



daysToDate :: Integer -> Int -> Int -> IO Integer
daysToDate year month day = daysAway $ fromGregorian year month day

      

Given an abbreviated function for a normally needed relative day:

tomorrow :: IO Day
tomorrow = fmap (addDays 1) today

      

We can demonstrate that Annie's thesis is correct:

ghci> tomorrow >>= daysAway
1

      

+4


source







All Articles