Haskell: How to pretty print number of seconds as

2019-09-05 04:27发布

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

2条回答
ゆ 、 Hurt°
2楼-- · 2019-09-05 05:00

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)
查看更多
倾城 Initia
3楼-- · 2019-09-05 05:13

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
查看更多
登录 后发表回答