[Haskell-cafe] TimeDiff to Int?

Philip Weaver philip.weaver at gmail.com
Wed Nov 12 12:43:33 EST 2008


2008/11/12 Lyle Kopnicky <lists at qseep.net>

> Hi folks,
>
> I had some code using the oldtime package, and want to convert it to use
> the time package.
>
> One of the things I need to do is calculate the number of seconds since
> midnight. The easy part is getting a TimeDiff result:
>
> utc <- getCurrentTime
> tz <- getCurrentTimeZone
> let td = timeOfDayToTime $ localTimeOfDay $ utcToLocalTime tz utc
>
> Now td is a TimeDiff representation of the number of seconds since
> midnight. It prints nicely, but I'm having a heck of a time figuring out how
> to truncate it to an Int.
>
> The floor function is only supported by the RealFrac class. Although
> TimeDiff has an instance of RealFrac and Fractional, it doesn't have an
> instance of RealFrac. I looked up the various to* and from* functions and
> have come up short. fromEnum yields an Int but it's the wrong value. I know
> I could use show and then use readS to get an Integer, or use formatTime
> (and reparse that), but that's a hack.
>
> I can convert it to a TimeOfDay which gives me hours, minutes, and seconds,
> but then I have to do arithmetic on it, and the seconds are of type Pico,
> which I can't call floor on either. I can convert it to a Rational via
> timeOfDayToDayFraction, but a TimeDiff is already a Rational those don't
> have floor.
>
> What am I missing? There has got to be an easy way to count seconds!
>

Well, you could always (read . takeWhile (not . (=='.')) . show), but here's
a better way:

   let x = toRational td
   in numerator x `div` denominator x

This was just the first thing I could come up with.  I bet there's a nicer
way.

- Phil


> Thanks,
> Lyle
>
>
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20081112/a965045b/attachment.htm


More information about the Haskell-Cafe mailing list