Printing NominalDiffTime in the form of hours, minutes and seconds

I am surprised that no one has asked about this before, but ... How can I trivially print NominalDiffTime in hours, minutes and seconds? (And maybe days if it takes so long ...)

For unknown reasons, the Show instance prints full seconds, which is obviously useless. (How much time is 13,055.22 seconds? Is it a few minutes? A day? Half an hour? I don’t know!)

There is a FormatTime class, but it does not apply to NominalDiffTime .

It seems you can use the floor method to get the total number of seconds as an actual number, but then what will you do with it?

As far as I can tell, DiffTime doesn't help either.

There must be a way to print the length of time ...

+7
formatting time haskell
source share
2 answers

You can print a DiffTime - which actually represents the duration and probably the type you should use - by going through TimeOfDay . Getting the right DiffTime hands DiffTime is actually a little tricky; you will need:

+2
source share

floor [1] gives you (as you say) the number of seconds that you can then use div and mod to convert to hours, minutes and seconds.

For example:

 floor ndt `div` 60 -- minutes, which may be more than 59 floor ndt `mod` 60 -- seconds 

[1], unlike fromEnum , which is a "conversion function" but does not convert to seconds, contrary to what the documentation says.

+1
source share

All Articles