【问题标题】:show remaining minutes instead of hours显示剩余分钟数而不是小时数
【发布时间】:2023-12-27 21:44:01
【问题描述】:

我需要你的帮助 显示剩余分钟数而不是小时数

15 分钟而不是 15:30

示例: 开始预订的剩余时间:15 分钟

 private Notification getNotification(Date countdownEnds) {
    DateFormat timeFormat = countdownTimeFormatFactory.getTimeFormat();
    String countdownEndsString = timeFormat.format(countdownEnds);
    String title = resources.getString(R.string.countdown_notification_title);
    String text = resources.getString(R.string.countdown_notification_text, countdownEndsString);

    PendingIntent tapIntent =
            PendingIntent.getActivity(context, 0, new Intent(context, MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
            .setContentTitle(title)
            .setContentText(text)
            .setTicker(title)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
            .setContentIntent(tapIntent)
            .setOngoing(true)
            .setAutoCancel(false);

    return builder.build();
}




   public DateFormat getTimeFormat() {
        return android.text.format.DateFormat.getTimeFormat(context);
    }

kod:code

【问题讨论】:

  • 15 分钟而不是 15:30。据我从您的问题 15 中了解到,这是没有意义的,是小时,而不是分钟
  • 是不是让15:30是倒计时结束的时间(或者下午3:30)而时间是15:15,所以还有15分钟,你要显示“ 15分钟”?你可以从Java Calculate time until event from current time获得很多灵感。请搜索更多有趣和有用的问题和答案。

标签: android date time notifications sleep-mode


【解决方案1】:

准系统解决方案:

    long remainingMillis = countdownEnds.getTime() - System.currentTimeMillis();
    long remainingMinutes = TimeUnit.MILLISECONDS.toMinutes(remainingMillis);
    String countdownEndsString = String.format("%d minutes", remainingMinutes);

要获得更好的解决方案,请使用现代 Java 日期和时间 API java.time 来计算分钟:

    long remainingMinutes = ChronoUnit.MINUTES.between(
            Instant.now(), DateTimeUtils.toInstant(countdownEnds));

在这种情况下,还要看看你是否可以完全摆脱 Date 的使用,因为该类早已过时,并且所有功能以及更多功能都在 java.time 中。在最后一个 sn-p 中,我使用了 ThreeTen Backport(参见下面的解释和链接)及其DateTimeUtils 类。对于阅读和使用 Java 8 或更高版本但仍未摆脱 Date 类的任何人,转换是内置在该类中的,因此它稍微简单一些:

    long remainingMinutes 
            = ChronoUnit.MINUTES.between(Instant.now(), countdownEnds.toInstant());

您可能还想查看java.timeDuration 类。

问题:我可以在 Android 上使用 java.time 吗?

是的,java.time 在较旧和较新的 Android 设备上都能正常工作。它只需要至少 Java 6

  • 在 Java 8 及更高版本以及更新的 Android 设备上(据我所知,从 API 级别 26 开始),现代 API 是内置的。
  • 在 Java 6 和 7 中,获取 ThreeTen Backport,即新类的后向端口(对于 JSR 310,ThreeTen;请参阅底部的链接)。
  • 在(较旧的)Android 上使用 ThreeTen Backport 的 Android 版本。它被称为 ThreeTenABP。并确保从 org.threeten.bp 导入日期和时间类以及子包。

链接

【讨论】: