显示剩余的分钟而不是小时

时间:2018-05-02 11:08:30

标签: android date time notifications sleep-mode

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

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

1 个答案:

答案 0 :(得分:0)

Barebones解决方案:

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

对于更好的解决方案,使用java.time,即现代Java日期和时间API,用于计算分钟数:

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

在这种情况下,还要看看你是否可以完全摆脱Date的使用,因为该类已经过时,所有功能都在java.time。在最后一个片段中,我使用的是ThreeTen Backport(请参阅下面的说明和链接)及其DateTimeUtils类。对于任何阅读和使用Java 8或更高版本但仍然没有摆脱Date类的人来说,转换是内置在该类中的,所以它稍微简单了:

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

您可能还想查看Duration的{​​{1}}类。

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

是的,java.time适用于较旧和较新的Android设备。它只需要至少Java 6

  • 在Java 8及更高版本和更新的Android设备上(来自API级别26,我被告知)现代API内置。
  • 在Java 6和7中获取ThreeTen Backport,新类的后端端口(适用于JSR 310的ThreeTen;请参阅底部的链接)。
  • On(较旧)Android使用Android版的ThreeTen Backport。它被称为ThreeTenABP。并确保使用子包从java.time导入日期和时间类。

链接