How can I format UTCTime / NominalDiffTime into a human readable representation?

Viewed 307

I've tried googling about but struggling to find a concrete example or which libraries I should be using for this.

I'd like to format a value of type NominalDiffTime (NominalDiffTime) for example as 05/10/2017 10:10AM.

2 Answers

Figured it out. I think there is some confusion because of the type alias: type POSIXTime = NominalDiffTime (https://hackage.haskell.org/package/time-1.8.0.3/docs/Data-Time-Clock-POSIX.html#t:POSIXTime).

import Data.Time.Clock
import Data.Time.Format
import Data.Time.Clock.POSIX

myFormatUtcTime :: UTCTime -> String
myFormatUtcTime = formatTime defaultTimeLocale "%H:%M %d/%m/%Y"

myFormatDiffTime :: NominalDiffTime -> String
myFormatDiffTime = formatTime defaultTimeLocale "%H:%M" . posixSecondsToUTCTime

I would recommend fmt library for time formatting.

  1. Human-readable names of functions instead of some strange formatting symbols sometimes.
  2. It can format not only time.

Example here:

ghci> import Data.Time (getZonedTime)
ghci> import Fmt.Time (dateDashF, dateSlashF)
ghci> t <- getZonedTime 
ghci> t
2017-10-05 14:53:08.818531 MSK
it :: ZonedTime
ghci> dateDashF t
"2017-10-05"
it :: Data.Text.Internal.Builder.Builder 
ghci> dateSlashF t
"10/05/17"
it :: Data.Text.Internal.Builder.Builder
Related