Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a Date variable in Elm

Tags:

elm

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?

like image 493
Batou99 Avatar asked Dec 08 '15 18:12

Batou99


1 Answers

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

like image 123
robertjlooby Avatar answered Oct 16 '22 10:10

robertjlooby