time icon indicating copy to clipboard operation
time copied to clipboard

Time.here practically useless

Open pschultz opened this issue 3 years ago • 3 comments

Time.here produces a timezone with fixed offset. Since time zones are only required when formatting times for humans this is useless for all values other than "right now", because we can't be sure that the offset "here" doesn't change in the next five minutes.

I want to display a time in the future in the browser's local time zone (in my case, Europe/Berlin). This seems to be impossible to do correctly. I understand that browsers don't have an API that allows to compute local times in arbitrary locations, but it is no problem to compute local times in the browser's configured location:

// Noon on December 1st 2020 in Berlin
new Date(1606820400000).getHours() == 12

I would expect Time.millisToPosix 1606820400000 |> Time.toHour tz (where tz is the Zone produced by Time.here) to return 12, but it returns 13 instead. I understand that Time.here produces a Time.Zone with a fixed UTC offset (currently +2 here in Berlin), but here where I am the offset isn't fixed (the offset is going to be +1 in December)! So Time.here is useless for any time on the other side of a DST change.

To summarize, Time.here is at the very least a misnomer (it's more like hereAndNow), but ideally it would produce correct local times for all inputs, which is possible to do with plain JavaScript as demonstrated above.

Complete program:

module Main exposing (main)

import Browser
import Html exposing (p, text)
import Task
import Time


type Msg
    = GotTZ Time.Zone


main =
    Browser.element
        { init = init
        , update = update
        , view = view
        , subscriptions = always Sub.none
        }


init : () -> ( Time.Zone, Cmd Msg )
init _ =
    ( Time.utc, Task.perform GotTZ Time.here )


update msg _ =
    case msg of
        GotTZ tz ->
            ( tz, Cmd.none )


view tz =
    let
        hour = 
            Time.millisToPosix 1606820400000 |> Time.toHour tz 
            -- Returns 13 at the time of writing (August 2020) in Europe/Berlin, but expected it to be 12.
    in
    p [] [ text <| String.fromInt hour ]

pschultz avatar Aug 04 '20 07:08 pschultz

Hi @pschult, I am also having problems with this, did you find any solution? Thank you.

tsmanuelanton avatar Feb 28 '24 17:02 tsmanuelanton

@tsmanuelanton, I don't recall what I ended up doing (I don't even know anymore what I was working on, exactly). If I had to guess: I probably used moment.js to do the formatting.

pschultz avatar Feb 29 '24 12:02 pschultz

@pschultz thank you for replying so fast. I found the package justinmimbs/time-extra wich does the work for me.

tsmanuelanton avatar Mar 03 '24 12:03 tsmanuelanton