Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell: Extract Int from POSIXTime / NominalDiffTime

I am signing web requests, and as part of the query string, I need to include oauth_timestamp=123456789 where the 123456789 is the nominal time since 1970-01-01 00:00 UTC.

I have been using POSIXTime for its representation, which is just a type alias for NominalDiffTime.

I am having problems when I want to convert the POSIXTime / NominalDiffTime to Text so that I can add it to the query string items collection.

The problem stems from the fact that the constructor for NominalDiffTime is private, and so I cannot extract the actual number.

Even the hacky way of using show will append an "s" generating 123456789s.

Is there a simple way of extracting the actual number from the NominalDiffTime?

like image 309
tmortiboy Avatar asked Mar 24 '16 01:03

tmortiboy


1 Answers

This might qualify as an example of typeclasses making APIs more esoteric than they have to be: NominalDiffTime implements RealFrac, the typeclass of arbitrary-precision fractions. As a result, the floor function is available to you:

λ> import Data.Time.Clock.POSIX
λ> pt <- getPOSIXTime
λ> pt
1458787669.804632s
λ> toRational pt
182348458725579 % 125000
λ> floor pt :: Int
1458787669
like image 169
hao Avatar answered Sep 30 '22 11:09

hao