How do I get the current time in Elm 0.17/0.18?

前端 未结 6 1985
悲哀的现实
悲哀的现实 2020-12-14 21:00

I had asked this question already:
How do I get the current time in Elm?

And answered it by writing my own (now deprecated) variant of start-ap

6条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-14 21:12

    You could create a Native module, and then expose a timestamp function that gets the time from Date.now() in JavaScript.

    This is roughly what it would look like:

    Timestamp.elm

    module Timestamp exposing (timestamp)
    
    import Native.Timestamp
    
    timestamp : () -> Int
    timestamp a = Native.Timestamp.timestamp a
    

    Native/Timestamp.js

    var _YourRepoUserName$your_repo$Native_Timestamp = function() {
      return { timestamp: function(a) {return Date.now()}
    }
    

    Main.elm

    port module Main exposing (..)
    
    import Timestamp exposing (timestamp)
    

    then you can use (timestamp ()) anywhere in Elm to get the current timestamp as an Int.


    Note: I used timestamp : () -> Int because I couldn't get it to work otherwise. timestamp : Int simply returned the hardcoded time of first load.

    Let me know if this could be improved.

提交回复
热议问题