module Network.API.TheMovieDB.Internal.Date
( Date (..),
parseDay,
(.::),
)
where
import Data.Aeson
import Data.Aeson.Types (Parser, typeMismatch)
import qualified Data.Text as Text
import Data.Time (Day (..), parseTimeM)
import Data.Time.Format (defaultTimeLocale)
newtype Date = Date {day :: Maybe Day} deriving (Eq, Show)
parseDay :: Object -> Text -> Parser (Maybe Day)
parseDay v key = do
m <- date
return (m >>= day)
where
date :: Parser (Maybe Date)
date = v .:? key <|> pure Nothing
(.::) :: Object -> Text -> Parser (Maybe Day)
(.::) = parseDay
instance FromJSON Date where
parseJSON Null = return (Date Nothing)
parseJSON (String t)
| Text.null t = return (Date Nothing)
| otherwise = do
d <- parseTimeM True defaultTimeLocale "%Y-%m-%d" (toString t)
return $ Date (Just d)
parseJSON v = typeMismatch "Date" v