Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a better way to convert from UTCTime to EpochTime?

I want to set a file's modification time to the time I got from exif data.

To get the time from exif, I found :

Graphics.Exif.getTag :: Exif -> String -> IO (Maybe String)

To set the file modification time, I found :

System.Posix.Files.setFileTimes :: FilePath -> EpochTime -> EpochTime -> IO ()

Assuming I do find a Time in Exif, I need to convert a String to an EpochTime.

  • With parseTime I can get a UTCTime.
  • With utcTimeToPOSIXSeconds I can get a POSIXTime
  • With a POSIXTime I can more or less get an EpochTime

To convert from a UTCTime to EpochTime this typechecks, but I'm not sure it's correct :

fromIntegral . fromEnum . utcTimeToPOSIXSeconds $ etime

This is part of a function getTime that will return the time from Exif data, if present, otherwise the file's modification time :

getTime (path,stat) = do
 let ftime                 = modificationTime $ stat
     err (SomeException _) = return ftime
 time <- liftIO $ handle err $ do
   exif <- Exif.fromFile path
   let getExifTime = MaybeT . liftIO . Exif.getTag exif
   res <- runMaybeT $ do
     tmp <- msum . map getExifTime $ [ "DateTimeOriginal","DateTimeDigitized", "DateTime" ]
     MaybeT . return . parseTime defaultTimeLocale "%Y:%m:%d %H:%M:%S" $ tmp
   case res of
     Nothing    -> return ftime
     Just etime -> return . fromIntegral . fromEnum . utcTimeToPOSIXSeconds $ etime
 return (path,time)

My question is

Is there a better/simpler way to convert the time ? ( maybe using different libaries )

like image 497
David V. Avatar asked Nov 16 '10 12:11

David V.


1 Answers

You can also use Data.Convertible.convert (from the convertible package):

import Data.Convertible (convert)
import System.Posix.Types (EpochTime(..))
import Data.Time.Clock (UTCTime(..))

utcTimeToEpochTime :: UTCTime -> EpochTime
utcTimeToEpochTime = convert
like image 103
Thedward Avatar answered Oct 18 '22 21:10

Thedward