2

Is there a Haskell library that can parse durations similar to these examples?

5 hours
5h 30m
1 d 5 h 30 m
PT12H30M5S
0

I wrote an small ISO duration parser:

{-# LANGUAGE FlexibleContexts #-}
import Control.Applicative
import qualified Text.Parsec as P
import Control.Lens

pInt = P.many P.digit <&> (\x -> read x :: Int)
pX letter multiplier = P.option 0  $ (pInt <&> (*) multiplier) <* P.char letter
pYear = pX 'Y' 31557600
pMon = pX 'M' 2629800
pDay = pX 'D' 86400
pHour = pX 'H' 3600
pMin = pX 'M' 60
pSec = pX 'S' 1

pTime = P.option 0 $ P.char 'T' *> sequence [pHour, pMin, pSec] <&> sum
pFull = P.char 'P' *> sequence [pYear, pMon, pDay, pTime] <&> sum

parseDuration = P.parse pFull "(source)"
parseDuration "PT1H"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.