所以我现在有了这个代码:
long diff = dateTwo.getTime() - dateOne.getTime();
long seconds = diff/1000;
long minutes = seconds/60;
long hours = minutes/60;
long days = hours/24;
long years = days/365;
这让我得到了以分钟,秒,天和年为单位的经过时间,但我希望有一个计时器显示如下:时间过去 - 1年,20天,5分钟,20秒。如何制作一个考虑闰年并正确显示数字的算法?
答案 0 :(得分:2)
您可以使用java.time.LocalDateTime的getter。
LocalDateTime now = LocalDateTime.now();
LocalDateTime past = LocalDateTime.of(someYear,someMonth...)
int year = now.getYear() - past.gerYear();
int month = now.getMonthValue() - past.getMonthValue();
int day = now.getDayOfMonth() - past.getDayOfMonth();
int hour = now.getHour() - past.getDayOfHour();
int minute = now.getMinute() - past.getMinute();
int second = now.getSecond() -past.getSecond();
int millis = now.get(ChronoField.MILLI_OF_SECOND) - past.get(ChronoField.MILLI_OF_SECOND);
注意你需要使用一些if else语句来检查哪个值更大并从中减去另一个
答案 1 :(得分:2)
我最终这样做了:
diff = dataDoi.getTime() - dataPrima.getTime();
x = TimeUnit.MILLISECONDS.toSeconds(diff);
seconds = x % 60;
x /= 60;
minutes = x % 60;
x /= 60;
hours = x % 24;
x /= 24;
days = x % 365;
x /= 365;
years = x;
每次潜水,只能获得剩余时间。
答案 2 :(得分:1)
你需要检查4年分的结果,因为当闰年除以4时我们将得到0:
if(years % 4 == 0) {
// to do something
}