How to get system time in Haskell using Data.Time.Clock?

Rafael S. Calsaverini picture Rafael S. Calsaverini · Jan 21, 2010 · Viewed 9.8k times · Source

I'm needing some Ints to use as seed to random number generation and so I wanted to use the old trick of using the system time as seed.

So I tried to use the Data.Time package and I managed to do the following:

import Data.Time.Clock

time = getCurrentTime >>= return . utctDayTime

When I run time I get things like:

Prelude Data.Time.Clock> time
55712.00536s

The type of time is IO DiffTime. I expected to see an IO Something type as this depends on things external to the program. So I have two questions:

a) Is it possible to somehow unwrap the IO and get the underlying DiffTime value?

b) How do I convert a DiffTime to an integer with it's value in seconds? There's a function secondsToDiffTime but I couldn't find its inverse.

Answer

Norman Ramsey picture Norman Ramsey · Jan 21, 2010

Is it possible to somehow unwrap the IO and get the underlying DiffTime value?

Yes. There are dozens of tutorials on monads which explain how. They are all based on the idea that you write a function that takes DiffTime and does something (say returning IO ()) or just returns an Answer. So if you have f :: DiffTime -> Answer, you write

time >>= \t -> return (f t)

which some people would prefer to write

time >>= (return . f) 

and if you have continue :: DiffTime -> IO () you have

time >>= continue

Or you might prefer do notation:

do { t <- time
   ; continue t  -- or possibly return (f t)
   }

For more, consult one of the many fine tutorals on monads.