Ahm*_*met 2 android time-format milliseconds simpledateformat kotlin
我有这个代码,但它还需要 2 个小时
val leftTimeInMillis = 12728918
val mTimeFormat = SimpleDateFormat("HH:mm:ss", Locale.ROOT)
binding.textTimeLeft.text = mTimeFormat.format(leftTimeInMillis)
Run Code Online (Sandbox Code Playgroud)
通常文本必须指示 03:32:08 但它是 05:32:08
使用 java.time(现代 Java 日期和时间 API)进行时间工作。
\n我还没有\xe2\x80\x99t 有一个Android 开发环境,但我希望以下内容可以与脱糖一起使用(请参阅下面的链接)。它适用于桌面 Java 版本 9 及更高版本。
\n int leftTimeInMillis = 12_728_918;\n \n Duration timeLeft = Duration.ofMillis(leftTimeInMillis);\n String formattedTimeLeft = String.format("%02d:%02d:%02d", \n timeLeft.toHours(), timeLeft.toMinutesPart(), timeLeft.toSecondsPart());\n \n System.out.println(formattedTimeLeft);\nRun Code Online (Sandbox Code Playgroud)\n输出为所需:
\n\n\n03:32:08
\n
如果出于某种原因您没有使用ThreeTenABP,而不是脱糖,我相信toMinutesPart和toSecondsPart方法不包括在内。然后转换需要更多一点:
Duration timeLeft = Duration.ofMillis(leftTimeInMillis);\n long hours = timeLeft.toHours();\n timeLeft = timeLeft.minusHours(hours);\n long minutes = timeLeft.toMinutes();\n timeLeft = timeLeft.minusMinutes(minutes);\n long seconds = timeLeft.getSeconds();\n String formattedTimeLeft = String.format("%02d:%02d:%02d", \n hours, minutes, seconds);\nRun Code Online (Sandbox Code Playgroud)\n输出与之前相同。
\n如果您\xe2\x80\x99 对日期和时间的广泛外部库感到满意,可以选择 Time4A,即 Time4J 的 Android 版本。它提供了一个更优雅、更符合您自己尝试的解决方案。我更喜欢声明一个静态格式化程序:
\nprivate static final Duration.Formatter<ClockUnit> M_TIME_FORMAT \n = Duration.formatter(ClockUnit.class, "hh:mm:ss");\nRun Code Online (Sandbox Code Playgroud)\n现在格式化如下:
\n int leftTimeInMillis = 12_728_918;\n \n Duration<ClockUnit> timeLeft = Duration.of(leftTimeInMillis, ClockUnit.MILLIS)\n .with(Duration.STD_CLOCK_PERIOD);\n String formattedTimeLeft = M_TIME_FORMAT.format(timeLeft);\n \n System.out.println(formattedTimeLeft);\nRun Code Online (Sandbox Code Playgroud)\n\n\n03:32:08
\n
我再次使用 Time4J 在桌面 Java 上开发了我的代码。
\n你的代码中发生了什么?这2个小时是从哪里来的?SimpleDateFormat设计于 1990\xe2\x80\x99s,始终用于格式化和解析时间点,而不是时间量。因此,您的数字 12 728 918 表示 UTC 1970 年 1 月 1 日开始的 Java 纪元之后这么多毫秒的时间点。换句话说,您正在尝试格式化 1970-01-01T03:32:08.918Z 的瞬间。由于您设备的时区设置(猜测是欧洲/雅典)在 1970 年冬天比 UTC 早 2 小时,因此用于格式化的日期和时间为 1970-01-01T05:32:08.918+02:00 [欧洲/雅典]。这就是你得到的原因05:32:08。
假设你没有想到 1970 年新年\xe2\x80\x99s 的夜晚,那么你所做的就是错误的,即使你能让它工作,它也会让每个阅读你代码的人感到困惑。另外,如果有一天毫秒数超过 24 小时,则不会打印整天,可能会造成很大的混乱。不要\xe2\x80\x99t 用于SimpleDateFormat此目的。并考虑根本不使用,SimpleDateFormat因为该类非常麻烦且早已过时。
java.time 在旧版和新版 Android 设备上都能很好地工作。它只需要至少Java 6。
\norg.threeten.bp。java.time。java.time到 Java 6 和 7(ThreeTen for JSR-310)。| 归档时间: |
|
| 查看次数: |
324 次 |
| 最近记录: |