I havenât dealt with dates yet but Iâm gonna assume youâre using this package.
The issue here is that youâre using Date (type) as a value. I highly recommend reading more about Elmâs types, and the differences between type constructors and data constructors for union types.
One way you can obtain the date is to pass it as an input argument from JS, as shown here.
You can also use Date.today function from the same package to perform a task in the init function, as seen here.
Conclusion: obtaining the date/time is an async operation (AKA side effect), and Elm, being a purely functional language, deals with them using the commands.
In addition to hrnxm comments, typically in Elm you can have a reasonable precise date/time value by having a âsubscriptionâ (see Commands and Subscriptions ¡ An Introduction to Elm) that runs periodically and ask the system for current date/time.
That way, you store the value in your Model.currentDate and use wherever you want in your app. Also, to avoid having to deal with Maybe's you can have a init value passed from JS (see reply above).
When I started with Elm, Iâve run into a similar problem: The init function runs only once, so why bother with tasks and subscriptions to do a simple thing like getting todayâs dateâespecially because you can be fairly certain that the date doesnât change during one session?
That put me off a little since in other languages itâs such a simple operation. The key for me was to realize that:
a) There is actually no guarantee that the init function is called only once. Itâs perfectly fine to call it later from my own code, e.g. to reset the model to an initial state. And then the guarantee that functions always return the same values when called with the same parameters (none in this case) would be broken.
b) The date might actually change during one session. It happens every day. So why would my code assume that it doesnât?
Keeping all functions side-effects free gives me all the power of Elm and the downsides of making init (or Date) special simply arenât worth it.
Maybe itâs obvious or long winded. Iâm just recounting my thought process back when I began using Elm. Hope it helps.
Another option if youâre starting out learning Elm and want to carry on quickly:
import Date
import Time exposing (Month(..)) -- comes from `elm install elm/time`
init : Model
init =
{ currentdate = Date.fromCalendarDate 2022 Jan 15 }
This will get you a hardcoded date value, but it might be helpful if you want to limit what youâre learning and just keep going right now.
If you are learning itâs totally okay to work up to to things like tasks/ports later!