Reputation: 2229
I have piece of code like this in my Haskell program:
...
start <- getCurrentTime
...
end <- getCurrentTime
...
delta = end `diffUTCTime` start
...
After this, delta
has type NominalDiffTime
. As written in the documentation, this type in inherited from Num
, and I want to print it with 3 (for example) places after decimal dot. However, using something like printf "%.3f" delta
doesn't work: No instance for (PrintfArg NominalDiffTime)
.
How to do this correctly?
Upvotes: 3
Views: 1552
Reputation: 9487
If you want a nicely formatted diff time, you can use System.Time.Utils (renderSecs)
together with round
ghci> import Data.Time.Clock
ghci> import System.Time.Utils (renderSecs)
ghci>
ghci> let renderS = renderSecs . round :: NominalDiffTime -> String
ghci> t1 <- getCurrentTime
ghci> -- wait a little :-P
ghci> t2 <- getCurrentTime
ghci> renderS $ t2 `diffUTCTime` t1
"2m15s"
It will also do days as d, and hours as h. Note that the type signature is mandatory for ghci, because otherwise it'll default to Double
, and suddenly you can't feed it NominalDiffTime
values.
Upvotes: 6
Reputation: 183868
You can convert it to a PrintfArg
type to print it in the desired format, e.g.
printf "%.3f" (realToFrac delta :: Double)
does it.
Upvotes: 6