nh2
nh2

Reputation: 25715

How to format UTCTime as ISO 8601 in Haskell

I would like to convert a full date/time to ISO 8601 format like JavaScript's new Date().toISOString() does, giving a YYYY-MM-DDTHH:mm:ss.sssZ format.

I cannot find a base library function or package to do this.

Upvotes: 15

Views: 3366

Answers (2)

nh2
nh2

Reputation: 25715

The time library in version 1.9 added this functionality (docs):

iso8601Show :: ISO8601 t => t -> String

and UTCTime has a ISO8601 instance.

ghci> import Data.Time
ghci> import Data.Time.Format.ISO8601
ghci> iso8601Show <$> getCurrentTime
"2023-11-18T14:58:56.371121983Z"

Upvotes: 6

jwodder
jwodder

Reputation: 57610

I don't see any pre-existing function for doing this, but you can make one easily using Data.Time.Format.formatTime:

import System.Locale (defaultTimeLocale)
import Data.Time.Format (formatTime)

iso8601 :: UTCTime -> String
iso8601 = formatTime defaultTimeLocale "%FT%T%QZ"

(You need to convert the time to a UTCTime before passing it to this function in order for it to actually display the actual UTC time.)

Upvotes: 17

Related Questions