Так что, если это 2 марта, и дата окончания - 3 мая, 2 часа дня, я хочу 2 месяца, 1 день и 1 час, оставшаяся , включая минуты и секунды). /> Я хочу иметь возможность получить оставшиеся месяцы до даты окончания, обращая внимание на дни месяца. Я не хочу, чтобы « 2 месяца оставались в среднем», чтобы означать, что 60 дней осталось, я хочу, чтобы это означало месяцы в римском календаре.
Количество дней в месяц в римском календаре
или
source wikipedia tabledia < /p>
Например:
, если это 2 январь, и это. Месяцы , вы собираетесь подумать « О, это 2 марта! Продолжительность класс. Проблема заключается в том, что
период < /strong> вычисляет его как даты (годы, месяцы), что означает, что он учитывает дни месяца, но это полностью игнорирует начало и конец времени < /em> событий, а
Продолжительность < /strong>. месяцы). < /p>
Вот пример кода: < /p>
Код: Выделить всё
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
public class Countdown {
private DateTimeFormatter dateTimeFormat;
private ZonedDateTime currentZDT;
private ZonedDateTime endZDT;
public Countdown() {
dateTimeFormat = DateTimeFormatter.ofPattern("EEEE, LLLL dd, yyyy, 'at' hh:mm a");
setDateTimes(2025, Month.JUNE, 5, 2, 36); // June 5th, 2025, at 2:36 AM
System.out.println(String.format("%-45s%s", "Current date/time:", currentZDT.format(dateTimeFormat)));
System.out.println(String.format("%-45s%s", "End event date/time:", endZDT.format(dateTimeFormat)));
System.out.println();
System.out.println(String.format("%-45s%s", "Elapsed Time using ChronoUnit:", remainingDays1()));
System.out.println(String.format("%-45s%s", "Elapsed Time using: ZonedDateTime.until():", remainingDays2()));
System.out.println(String.format("%-45s%s", "Elapsed Time using the Duration Class:", remainingTimeDuration()));
System.out.println(String.format("%-45s%s", "Elapsed Time using the Period Class:", remainingTimePeriod()));
}
private void setDateTimes(int endYear, Month endMonth, int endDOM /* Day of Month */,
int endHour /* In 24-hour format */, int endMinute) {
ZoneId currentZone = ZoneId.systemDefault();
currentZDT = Instant.now().atZone(currentZone);
LocalDate endDate = LocalDate.of(endYear, endMonth, endDOM);
LocalTime endTime = LocalTime.of(endHour, endMinute);
endZDT = ZonedDateTime.of(endDate, endTime, currentZone);
}
// This returns part of what I need
public String remainingTimePeriod() {
/*
* Period DOES take into account the differences in the number of days in a
* month
* BUT it disregards the time of the current and end ZDT
*/
Period per = Period.between(LocalDate.from(currentZDT), LocalDate.from(endZDT));
int days = per.getDays();
int months = per.getMonths();
int years = per.getYears();
return String.format("%d year(s), %d month(s), and %d day(s)", years, months, days);
}
// This returns the other part
public String remainingTimeDuration() {
//Duration doesn't even have a way to get months
Duration dur = Duration.between(currentZDT, endZDT);
long days = dur.toDaysPart();
long hours = dur.toHoursPart();
long minutes = dur.toMinutesPart();
long seconds = dur.toSecondsPart();
return String.format("%02d day(s), %02d hour(s), %02d minute(s), and %02d second(s) left", days, hours, minutes,
seconds);
}
/*
* These return the total time left in 1 unit (it cant be spread across multiple)
*/
public long remainingDays1() {
return ChronoUnit.DAYS.between(currentZDT, endZDT);
}
public long remainingDays2() {
return currentZDT.until(endZDT, ChronoUnit.DAYS);
}
}
Код: Выделить всё
Current date/time: Sunday, May 04, 2025, at 02:37 AM
End event date/time: Thursday, June 05, 2025, at 02:38 AM
Elapsed Time using ChronoUnit: 32
Elapsed Time using: ZonedDateTime.until(): 32
Elapsed Time using the Duration Class: 32 day(s), 00 hour(s), 00 minute(s), and 31 second(s) left
Elapsed Time using the Period Class: 0 year(s), 1 month(s), and 1 day(s)
< /code>
и < /p>
Current date/time: Sunday, May 04, 2025, at 02:37 AM
End event date/time: Thursday, June 05, 2025, at 02:36 AM
Elapsed Time using ChronoUnit: 31
Elapsed Time using: ZonedDateTime.until(): 31
Elapsed Time using the Duration Class: 31 day(s), 23 hour(s), 58 minute(s), and 21 second(s) left
Elapsed Time using the Period Class: 0 year(s), 1 month(s), and 1 day(s)
Подробнее здесь: https://stackoverflow.com/questions/796 ... -date-time