更新时间:2022-05-09 06:00:20
ZoneId zone = ZoneId.of("Europe/Busingen");
DayOfWeek alarmDay = DayOfWeek.SUNDAY;
LocalTime alarmTime = LocalTime.of(14, 20);
ZonedDateTime now = ZonedDateTime.now(zone);
ZonedDateTime alarmDateTime = now.with(alarmDay).with(alarmTime);
if (alarmDateTime.isBefore(now)) {
alarmDateTime = alarmDateTime.plusWeeks(1);
}
Duration difference = Duration.between(now, alarmDateTime);
String toastMessage = String.format(" %d Days %d Hours %d Minutes",
difference.toDaysPart(), difference.toHoursPart(), difference.toMinutesPart());
System.out.println(toastMessage);
刚刚跑步(星期日 22:03:17 在 Büsingen)我得到了:
Running just now (Sunday 22:03:17 in Büsingen) I got:
6 天 16 小时 16 分钟
6 Days 16 Hours 16 Minutes
我相信我提供的答案不仅是现代的,而且是更可靠的.
I believe that I am contributing the answer that is not only the modern one but also the more robust one.
Calendar
类早已过时,按照今天的标准设计很差.相反,我使用并推荐 java.time
,现代 Java 日期和时间 API.ZonedDateTime
对象可以最大限度地减少意外.它确实需要您填写您想要的时区,因为夏季时间转换是特定于时区的.日历
、日期和时间作为每周重复的闹钟似乎有点有趣.您需要的是星期几和一天中的某个时间,所以我使用它.java.time
提供所需的类,DayOfWeek
枚举和 LocalTime
类.Calendar
class is long outdated and by today’s standards poorly designed. Instead I use and recommend java.time
, the modern Java date and time API.ZonedDateTime
objects minimizes surprises here. It does require you to fill in your desired time zone where I put Europe/Busingen since summer time transitions are time zone specific.Calendar
, a date and time, for a weekly recurring alarm seems a bit funny. What you need is a day-of-week and a time of day, so I use that. java.time
offers the classes needed, the DayOfWeek
enum and the LocalTime
class.事实上,我是如此现代,以至于我使用了 Java 9 中引入的 Duration
类的 toXxxPart
方法.用于格式化 Duration
如果您还没有使用 Java 9,则需要先从持续时间中减去天数以获得小时数:使用 minusDays
方法.然后用 minusHours
类似地得到分钟.
I am in fact so modern that I am using the toXxxPart
methods of the Duration
class that were introduced in Java 9. For formatting the Duration
if you are not yet using Java 9 you will need to subtract first the days from the duration to get the hours: use the minusDays
method. Then do similarly with minusHours
to get the minutes.
long toDays = difference.toDays();
difference = difference.minusDays(toDays);
long toHours = difference.toHours();
difference = difference.minusHours(toHours);
long toMinutes = difference.toMinutes();
是的,java.time
在新旧 Android 设备上运行良好.它只需要至少 Java 6.
Yes, java.time
works nicely on older and newer Android devices. It just requires at least Java 6.
org.threeten.bp
导入日期和时间类.org.threeten.bp
with subpackages.java.时间
.java.time
首先被描述.java.time
向后移植Java 6 和 7(JSR-310 为 ThreeTen).java.time
.java.time
was first described.java.time
to Java 6 and 7 (ThreeTen for JSR-310).