10

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?

1 Answer 1

14

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.

Ignore it

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.

Use it

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 Results

2
  • In repl , Date.fromString "2011/1/1" |> Result.withDefault (Date.fromTime 0) return : {} : Date.Date. Still no date...
    – BoumTAC
    Jun 16, 2016 at 21:52
  • The Date.Date type just doesn't toString well and shows up as {}. If you try (Date.fromString "2011/1/1" |> Result.withDefault (Date.fromTime 0) |> (\d -> (Date.year d, Date.month d, Date.day d))) you should see (2011,Jan,1) : ( Int, Date.Month, Int ) Jun 17, 2016 at 1:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.