1

I'm looking for a way to represent the current time in Haskell like can do in Ruby:

Time.now.to_i
 => 1405771733

I tried this:

import Data.Time.Clock
currTime <- getCurrentTime

let timed = floor $ utctDayTime currTime :: Int -- 1
let timed = utctDayTime currTime :: Int -- 2

The first expression returned 43774 which didn't look like it was the right answer.

Baldrick
  • 23,882
  • 6
  • 74
  • 79
Incerteza
  • 32,326
  • 47
  • 154
  • 261

2 Answers2

4

Use the Data.Time.Clock.POSIX module in the time package:

main :: IO ()
main = print =<< getPOSIXTime

This function returns an PosixTime (in the IO monad), which you can convert to an Integer with round or floor.

MasterMastic
  • 20,711
  • 12
  • 68
  • 90
Twan van Laarhoven
  • 2,542
  • 15
  • 16
1

tl;dr

Ruby's #to_i method returns the number of seconds since the UNIX Epoch (January 1, 1970 00:00 UTC). You can return the same number with the following function:

secondsFromEpoch :: UTCTime -> Int
secondsFromEpoch utc =
    let seconds = formatTime defaultTimeLocale "%s" utc
    in  read seconds

used as:

main :: IO ()
main = do
    currentTime <- getCurrentTime
    print $ secondsFromEpoch currentTime

Live demo

How does this work

To understand this solution you can just read the Date.Time.Format documentation, specifically at the formatTime function:

%s

number of whole seconds since the Unix epoch. For times before the Unix epoch, this is a negative number. Note that in %s.%q and %s%Q the decimals are positive, not negative. For example, 0.9 seconds before the Unix epoch is formatted as -1.1 with %s%Q.

Therefore:

formatTime defaultTimeLocale "%s" utc

will return the number of seconds in a string. Since it's an integer, we can use read and put it into an Int.

Where was your mistake

An UTCTime is composed of:

  • a Day (a day)
  • a DiffTime (time from midnight)

The function utctDayTime has the following type:

utctDayTime :: UTCTime -> DiffTime

that is: it takes an UTCTime and returns the number of seconds from midnight. Therefore utctDayTime does not account for the day.

Community
  • 1
  • 1
Shoe
  • 74,840
  • 36
  • 166
  • 272