[Haskell-cafe] Parsing LocalTime from Unix seconds

Alexander V Vershilov alexander.vershilov at gmail.com
Fri Sep 14 08:27:16 UTC 2018


Hi Marc,

The best way of answering such questions is to check the source code.
Hackage provides
a nice way of doing that -  click on 'Source' near the instance that
you are interested in:

https://hackage.haskell.org/package/time-1.6.0.1/docs/Data-Time-Format.html#t:ParseTime

And you'll see the implementation

```

instance ParseTime LocalTime where
    buildTime l xs = LocalTime <$> (buildTime l xs) <*> (buildTime l xs)
```

That builds time from `Day` and `TimeOfDay` passing your parse string
to each of those.
Then you can check ParseTime instance of Day:

https://hackage.haskell.org/package/time-1.6.0.1/docs/src/Data.Time.Format.Parse.html#line-331

I'm not providing it here, as it's quite big, but the main point is
that `s` is ignored so in that case
Day appear to be:

```
            rest (YearMonth m:_) = let
                d = safeLast 1 [x | MonthDay x <- cs]
                in fromGregorianValid y m d
```
with y=m=d=1

if you continue the process for TimeOfDay you'll find that `s` is
ignored there as well, and
`midnight = TimeOfDay 0 0 0` is returned in that case.

So it appeared that LocalTime consists of the components that ignore
your parse string and return
default value instead.

I don't know if that is intended behaviour or not, but for me it makes
more sense to parse to UTCTime/POSIXTime
and then convert into LocalTime, in case if you get seconds as input.

Hope that helps.


On Thu, 6 Sep 2018 at 13:42, Marc Busqué <marc at lamarciana.com> wrote:
>
> In GHCi
>
> ```
> :m +Data.Time
> parseTimeM True defaultTimeLocale "%s" "1535684406" :: Maybe UTCTime
> -- => Just 2018-08-31 03:00:06 UTC
> parseTimeM True defaultTimeLocale "%s" "1535684406" :: Maybe LocalTime
> -- => Just 1970-01-01 00:00:00
> ```
>
> Why? ¯\(°_o)/¯
>
> Marc Busqué
> http://waiting-for-dev.github.io/about/_______________________________________________
> Haskell-Cafe mailing list
> To (un)subscribe, modify options or view archives go to:
> http://mail.haskell.org/cgi-bin/mailman/listinfo/haskell-cafe
> Only members subscribed via the mailman list are allowed to post.



-- 
Alexander


More information about the Haskell-Cafe mailing list