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...


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.

  • 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.

    链接地址: http://www.djcxy.com/p/86002.html

    上一篇: Rails 4 + Rolify Gem:用户角色没有通过UI更新

    下一篇: 以小时,分钟和秒为单位打印NominalDiffTime