Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print NominalDiffTime as hours, minutes and seconds

I'm surprised nobody has asked this before, but... How do I trivially print a NominalDiffTime as hours, minutes and seconds? (And possibly days, if it happens to be that long...)

For reasons unknown, the Show instance prints total seconds, which is obviously useless. (How long is 13,055.22 seconds? Is that a few minutes? A day? Half an hour? I have no idea!)

There's the FormatTime class, but it doesn't apply to NominalDiffTime.

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

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

There must be a way to print time durations sanely...

like image 491
MathematicalOrchid Avatar asked Jun 27 '15 09:06

MathematicalOrchid


2 Answers

You can print a DiffTime -- which actually represents a duration, and is likely the type you should be using -- by going through TimeOfDay. Getting your hands on a DiffTime correctly is actually a little bit tricky; you'll need:

  • A leap second table. type documentation, a page with a leap second table; you'll want to have a way for your program to read this in at runtime, as these change every few months.
  • From there, you can use utcToTAITime to convert to AbsoluteTime, and
  • diffAbsoluteTime to get a DiffTime, and
  • timeToTimeOfDay to have the library do your divmod's for you, and finally
  • formatTime to print this.
like image 165
Daniel Wagner Avatar answered Oct 07 '22 00:10

Daniel Wagner


floor[1] gives you (as you say) the number of seconds, which you can then use div and mod to convert into 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 doesn't convert to seconds, contrary to what the documentation says.

like image 41
Robin Green Avatar answered Oct 07 '22 01:10

Robin Green