我需要你的帮助 显示剩余的分钟而不是几小时
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
答案 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}}类。
是的,java.time
适用于较旧和较新的Android设备。它只需要至少Java 6 。
java.time
导入日期和时间类。org.threeten.bp
。java.time
。java.time
向Java 6和7的后端(JST-310的ThreeTen)。