Search code examples
datetimeoffsetelm

How can I display current Timezone offset in GMT, in Elm


I'm stuck on getting the current Timezone offset from the Date in Elm.

Date.now

This returns <Thu Feb 22 2018 20:42:42 GMT+0530 (India Standard Time)> as string As I have explored in Elm's core lib of date and time, and they don't provide any direct method to fetch the current timezone offset. So what should I do?

import Html as App
import Html exposing (..)
import Date exposing (Date)
import Task


type alias Model = 
  Maybe Date


type Msg = 
  SetDate (Maybe Date)


update : Msg -> Model -> (Model, Cmd Msg)
update (SetDate date) _ = 
  (date, Cmd.none)


view : Model -> Html Msg
view model =
  div [] [ text <| dateString model ]


dateString : Model -> String
dateString model =
  case model of
    Nothing -> "No date here"
    Just date ->
      (toString <| date)

now : Cmd Msg
now = 
  Task.perform (Just >> SetDate) Date.now




main : Program Never Model Msg
main =
  App.program 
    { init = ( Nothing, now ) 
    , view = view
    , subscriptions = always Sub.none 
    , update = update
    }

I need this +0530 as in the float 5.5.


Solution

  • Elm's DateTime functions are pretty sparse at the moment, but justinmimbs Date.Extra library is my go to for this type of problem. Check it out here

    You can import it as such,

    import Date.Extra exposing (offsetFromUtc)
    

    And, then where you had toString <| date change your pipeline to

    date
        |> offsetFromUtc
        |> toString
    

    That'll give you your offset in minutes, if you want the float value, just divide the int by 60. Simple function here to do so:

    divBy60 : Int -> Float
    divBy60 t =
        toFloat t / 60.0
    

    then just change your pipeline again to

    date
        |> offsetFromUtc
        |> divBy60
        |> toString