Cookbook/Dates And Time

From HaskellWiki
< Cookbook
Revision as of 14:33, 12 January 2014 by Artyom Kazak (talk | contribs)
Jump to navigation Jump to search
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.

Finding today's date

import Data.Time

c <- getCurrentTime                  --> 2009-04-21 14:25:29.5585588 UTC 
(y,m,d) = toGregorian $ utctDay c    --> (2009,4,21)

Adding to or subtracting from a date

Problem Solution Examples
adding days to a date addDays
import Data.Time
a = fromGregorian 2009 12 31    --> 2009-12-31
b = addDays 1 a                 --> 2010-01-01
subtracting days from a date addDays
import Data.Time
a = fromGregorian 2009 12 31    --> 2009-12-31
b = addDays (-7) a              --> 2009-12-24

Difference of two dates

Problem Solution Examples
calculating the difference of two dates diffDays
import Data.Time
a = fromGregorian 2009 12 31    --> 2009-12-31
b = fromGregorian 2010 12 31    --> 2010-12-31
diffDays b a                    --> 365

CPU time

Use System.CPUTime.getCPUTime to get the CPU time in picoseconds.

You can time a computation like this

getCPUTimeDouble :: IO Double
getCPUTimeDouble = do t <- System.CPUTime.getCPUTime; return ((fromInteger t) * 1e-12)

main = do
    t1 <- getCPUTimeDouble
    print (fib 30)
    t2 <- getCPUTimeDouble
    print (t2-t1)