cornihilio
cornihilio

Reputation: 83

How do I convert from unixtime to a date/time in Haskell?

So, the setup is that I have the time, in seconds, since the epoch and I want to turn this into a date I can actually understand. How do I do this in Haskell? If it is possible, how would I extract days/hours/minutes out of this new encoding?

Upvotes: 8

Views: 2461

Answers (2)

nponeccop
nponeccop

Reputation: 13677

Use time library which is installed by default:

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

main = print $ formatTime defaultTimeLocale  "%c" $ posixSecondsToUTCTime 10

The library has wide range of date manipulation functions (e.g. date subtraction, getting components such as day-month etc). If you want to extract components just for converting them to string you can use formatTime.

Upvotes: 5

singpolyma
singpolyma

Reputation: 11262

Data.Time.Clock.POSIX has posixSecondsToUTCTime (you can convert another numeric type to the input expected POSIXTime with realToFrac).

Data.Time.Calendar has a lot of the things you need to extract day, month, etc from the Day that forms a part of UTCTime, the rest of the package has other useful utilities.

Example:

Prelude> import Data.Time.Format.ISO8601
Prelude Data.Time.Format.ISO8601> import Data.Time.Clock.POSIX 
Prelude Data.Time.Format.ISO8601 Data.Time.Clock.POSIX> iso8601Show $ posixSecondsToUTCTime $ 100
"1970-01-01T00:01:40Z"

Upvotes: 11

Related Questions