I want to add/subtract given number of minutes to/from given given time and find out the resulting time.
e.g. Suppose the given time is 11:30AM and number of minutes to add are 100 then the resulting time is 01:10PM
How to do it in Haskell using the Data-Time library? I tried reading the docs on the Haskell site but couldn't get almost anything out of it.
There is no example shown on that documentation site. Also the cookbook on the Haskell site doesn't contain any example for time calculations.
Edit: no need for current time, it should work for any given time. Time may be given as a string like "11:30".
2 Answers 2
A sample demo of adding 100 minutes:
λ> import Data.Time
λ> currentTime <- getCurrentTime
λ> currentTime
2016年10月02日 10:27:03.30961 UTC
λ> currentZone <- getCurrentTimeZone
λ> currentZone
IST
λ> utcToLocalTime currentZone currentTime
2016年10月02日 15:57:03.30961
λ> let hundredMinutes = 100 * 60
λ> addUTCTime hundredMinutes currentTime
2016年10月02日 12:07:03.30961 UTC
λ> let newTime = addUTCTime hundredMinutes currentTime
λ> utcToLocalTime currentZone newTime
2016年10月02日 17:37:03.30961
The addUTCTime function is used for adding 100 minutes. (削除) An equivalent function for subtracting is also available. (削除ここまで)
8 Comments
diffUtcTime as a different signature than addUTCTime .hundredMinutes as - 100 * 60. :)LocalTime or UTCTime.You can use Data.Time.Clock.getCurrentTime to fetch the current time. This returns IO UTCTime.
You can then use Data.Time.Clock.addUTCTime to add minutes to this previously fetched time.
import Data.Time
currentTimePlusMinutes minutes = getCurrentTime
>>= (\time -> return (addUTCTime (minutes * 60) time))
If you don't want to use the current time, you can then simply do
addMinutes :: NominalDiffTime -> UTCTime -> UTCTime
addMinutes minutes = addUTCTime (minutes * 60)
λ> addMinutes 10 time
2016年10月02日 12:41:09.68297 UTC
7 Comments
>>= (\t -> ...) notation is the best way to write this. Anyone has recommandations?addMinutes 10 time?:t addMinutes within ghci. In this instance, it outputs addMinutes :: NominalDiffTime -> UTCTime -> UTCTime, so time needs to be a UTCTime.
dayFractionToTimeOfDayand its inverse, but you can't cross midnights that way.UTCTime(timestamp) andNominalDiffTime(duration). Maybe they indeed could do with vector-spaces instances.