How to create a Date variable in Elm

I want to hardcode the date in the elm record. Record signature

type alias Record = { .., startDate : Date, .. } 

In my code I do

 record = { .., startDate = Date.fromString "2011/1/1", .. } 

The problem is that the record type assumes the date type, but the Date .fromString signature

 String -> Result.Result String Date.Date 

How can I create a Date to use in the Record type?

+8
elm
source share
1 answer

You get Result because there is a chance that the parsing of the string before the date failed. You can handle this in one of two ways.

Ignore him

If you just want to say, β€œI know that this string will be a valid date, and I'm not worried that I may have messed it up,” you can simply specify the default date

 Date.fromString "2011/1/1" |> Result.withDefault (Date.fromTime 0) 

This will leave you with a Date , but by default the unix era will be used if the parsing fails.

Use it

Think about what you would like to do if the parsing was to fail and process it where the date is used. Ex. if you show it as a string, you can display the date or if the parsing does not display "TBA" .

Note You may have noticed that Date.fromTime just returns Date not a Result (because Int can always be parsed to Date ). If you don't mind converting your dates to timestamps unix, you can hard-set the timestamp and use it without having to deal with Result s

+11
source share

All Articles