I want to hardcode a date in a record in elm. The record signature is
type alias Record = { .., startDate : Date, .. }
On my code I am doing
record = { .., startDate = Date.fromString "2011/1/1", .. }
The problem is that the Record type expects a Date type but Date.fromString signature is
String -> Result.Result String Date.Date
How can I create the Date to use on the Record type?
You're getting the Result
because there is a chance that parsing the string to a date failed. You can handle it one of 2 ways.
If you want to just say "I know this string will be valid date and I'm not worried that I may have messed it up" then you can just provide a default date
Date.fromString "2011/1/1" |> Result.withDefault (Date.fromTime 0)
This will leave you with a Date
but will default to the unix epoch if the parse fails.
Think about what you would want to happen if the parse were to fail and handle it where the date is used. Ex. if you're displaying it as a string you could display the date or if the parse failed display "TBA"
.
Note: You may have noticed that Date.fromTime
just returns a Date
not a Result
(because an Int
can always be parsed to a Date
). If you don't mind converting your dates to unix timestamps you could hardcode the timestamp and use that without having to deal with Result
s
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With