Skip to content

Instantly share code, notes, and snippets.

@l1x

l1x/DateTime.elm

Last active Apr 8, 2020
Embed
What would you like to do?
Displaying Date and Time (zero padded values)
-- Show the current time in your time zone.
--
-- Read how it works:
-- https://guide.elm-lang.org/effects/time.html
import Browser
import Html exposing (..)
import Task
import Time exposing (..)
-- MAIN
main =
Browser.element
{ init = init
, view = view
, update = update
, subscriptions = subscriptions
}
-- MODEL
type alias Model =
{ zone : Time.Zone
, time : Time.Posix
}
init : () -> (Model, Cmd Msg)
init _ =
( Model Time.utc (Time.millisToPosix 0)
, Task.perform AdjustTimeZone Time.here
)
-- UPDATE
type Msg
= Tick Time.Posix
| AdjustTimeZone Time.Zone
update : Msg -> Model -> (Model, Cmd Msg)
update msg model =
case msg of
Tick newTime ->
( { model | time = newTime }
, Cmd.none
)
AdjustTimeZone newZone ->
( { model | zone = newZone }
, Cmd.none
)
-- SUBSCRIPTIONS
subscriptions : Model -> Sub Msg
subscriptions _ =
Time.every 1000 Tick
-- VIEW
zeroPadedStringfromInt : Int -> String
zeroPadedStringfromInt x =
if x > 0 && x < 10 then
"0" ++ String.fromInt x
else
String.fromInt x
monthToString : Month -> String
monthToString month =
case month of
Jan -> "01"
Feb -> "02"
Mar -> "03"
Apr -> "04"
May -> "05"
Jun -> "06"
Jul -> "07"
Aug -> "08"
Sep -> "09"
Oct -> "10"
Nov -> "11"
Dec -> "12"
view : Model -> Html Msg
view model =
let
-- Date
year = String.fromInt (Time.toYear model.zone model.time)
month = monthToString (Time.toMonth model.zone model.time)
day = zeroPadedStringfromInt (Time.toDay model.zone model.time)
-- Time
hour = zeroPadedStringfromInt (Time.toHour model.zone model.time)
minute = String.fromInt (Time.toMinute model.zone model.time)
second = zeroPadedStringfromInt (Time.toSecond model.zone model.time)
in
h1 [] [ text (year ++ "." ++ month ++ "." ++ day ++ " " ++ hour ++ ":" ++ minute ++ ":" ++ second) ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.