Haskell: how to add minutes to current time using

2019-07-20 08:30发布

问题:

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".

回答1:

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.



回答2:

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