Haskell: How to pretty print number of seconds as

2019-09-05 05:08发布

问题:

I have an integral value that is the number of seconds since the Epoch. I can output it as a big integer, but I want to show it as a human-readable date and time.

For example:

secToTimestamp :: Int32 -> [Char]

which returns something like:

2016-01-01 14:11:11

回答1:

In the interests of having a simple time based solution (since time is the defacto module for manipulating anything time related):

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

secToTimestamp :: Int32 -> String
secToTimestamp = formatTime defaultTimeLocale "%F %X" . posixSecondsToUTCTime . fromIntegral


回答2:

Possible use unix-time module

{-# LANGUAGE OverloadedStrings #-}
import           Prelude
import qualified Data.ByteString.Char8  as B
import           Data.UnixTime
import           Data.Int
import           Data.Functor

secToTimestampGMT :: Int32 -> [Char]
secToTimestampGMT t = B.unpack $ formatUnixTimeGMT "%Y-%m-%d %H-%M-%S" $ UnixTime (fromIntegral t) 0

secToTimestamp :: Int32 -> IO [Char]
secToTimestamp t = B.unpack <$> (formatUnixTime "%Y-%m-%d %H-%M-%S" $ UnixTime (fromIntegral t) 0)