问题描述
基本上,我试图根据两个 UNIX 时间戳的差异创建倒计时。
我的目标是创建一个这样的倒计时:130:04:23
130 是小时,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 小时的日期。日期之间的负毫秒数也不起作用。
解决方法
解决方案是使用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