[Haskell-cafe] TimeDiff to Int?

Lyle Kopnicky lists at qseep.net
Wed Nov 12 17:29:22 EST 2008


Thanks Philip and Roger,

I think I'll use...

  floor $ toRational td

...although I could have sworn that didn't work last night. I don't see that
TimeDiff has an instance of RealFrac, where floor is defined, though it does
have a instances of Real and Fractional.

Yes, the numeric classes are a bit hard to follow. Especially confusing is
the conversions. I'm thinking of making a multiparameter Coercible class,
with a coerce function, to help address that.

- Lyle

On Wed, Nov 12, 2008 at 9:43 AM, Philip Weaver <philip.weaver at gmail.com>wrote:

>
>
> 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/c571d0c2/attachment.htm


More information about the Haskell-Cafe mailing list