Get Unix / Epoch time as Int

There is also the solution discussed in Real World Haskell:

import System.Time
getClockTime >>= (\(TOD sec _) -> return sec)

How about:

import Data.Time.Clock.POSIX (getPOSIXTime)

timeNanos, timeMicros, timeMillis :: IO Integer

t mul = round . (mul *) <$> getPOSIXTime
timeNanos  = t 1000000000
timeMicros = t 1000000
timeMillis = t 1000

main = do
  tNanos  <- timeNanos
  tMicros <- timeMicros
  tMillis <- timeMillis

  print tNanos
  print tMicros
  print tMillis

-- OUT:
-- 1539161680010615122
-- 1539161680010617
-- 1539161680011

Yes.

getCurrentTime :: IO UTCTime.

UNIX epoch time could be retrieved as Int like that:

> :m + Data.Time System.Locale Control.Applicative
> epoch_int <- (read <$> formatTime defaultTimeLocale "%s" <$> getCurrentTime) :: IO Int
> epoch_int
1375025861

UPD: as other users noticed, there is much more simple way to do that:

> :m + Data.Time.Clock.POSIX
> round `fmap` getPOSIXTime 
1375040716
it :: Integer

Try this:

import Data.Time
import Data.Time.Clock.POSIX

t = getPOSIXTime

It has 6 decimal places of accuracy.

Tags:

Haskell