首页 > 解决方案 > 从两个 posix 时间戳在 Elm 中创建倒计时

问题描述

基本上我试图从两个 UNIX 时间戳的差异中创建倒计时。

我的目标是创建这样的倒计时:130:04:23130 是小时,04 是分钟,23 是两个日期之间的秒数。

toCountDown : Time.Posix -> Time.Posix -> String
toCountDown now end =
    let
        differenceMillis =
            Time.posixToMillis end - Time.posixToMillis now
        hour =
            String.fromInt (differenceMillis // 1000 // 60 // 60)
        minute =
            String.fromInt (remainderBy 60 (differenceMillis // 1000 // 60))
        second =
            String.fromInt (remainderBy 60 (differenceMillis // 1000))
    in
    hour ++ ":" ++ minute ++ ":" ++ second

我的代码适用于相隔不到 24 小时但不超过 24 小时的日期。日期之间的负毫秒数也不起作用。

标签: elm

解决方案


解决方法是使用modBy,而不是remainderBy。因此正确的代码是:

toCountDown : Time.Posix -> Time.Posix -> String
toCountDown now end =
    let
        differenceMillis =
            Time.posixToMillis end - Time.posixToMillis now
        hour =
            String.fromInt (differenceMillis // 1000 // 60 // 60)
        minute =
            String.fromInt (modBy 60 (differenceMillis // 1000 // 60))
        second =
            String.fromInt (modBy 60 (differenceMillis // 1000))
    in
    hour ++ ":" ++ minute ++ ":" ++ second

推荐阅读