module Common.Util.Time
  ( timeToDay
  , parseDay
  ) where

import           Data.Text           (Text)
import qualified Data.Text           as T
import           Data.Time           (UTCTime)
import qualified Data.Time           as Time
import           Data.Time.Calendar  (Day)
import           Data.Time.LocalTime
import qualified Text.Read           as T

timeToDay :: UTCTime -> IO Day
timeToDay time = localDay . (flip utcToLocalTime time) <$> getTimeZone time

parseDay :: Text -> Maybe Day
parseDay str = do
  (y, m, d) <-
    case T.splitOn "-" str of
      [y, m, d] -> Just (y, m, d)
      _         -> Nothing
  d' <- T.readMaybe . T.unpack $ d
  m' <- T.readMaybe . T.unpack $ m
  y' <- T.readMaybe . T.unpack $ y
  return $ Time.fromGregorian y' m' d'