减去两个日期值并返回不同的天数[重复]

时间:2022-08-25 18:13:24

This question already has an answer here:

这个问题在这里已有答案:

Bearing the risk of being redundant, I would like to know how one can subtract 2 date values and store the result which should be in number of days into an integer. I am using Java for this exercise.

承担冗余的风险,我想知道如何减去2个日期值并将结果存储在整数中。我正在使用Java进行此练习。

2 个解决方案

#1


1  

If you have two LocalDates, you can use:

如果您有两个LocalDates,则可以使用:

longs days = ChronoUnit.DAYS.between(date1, date2);

Note that Period::getDays does something different: for a period of one year and one day, Period::getDays will return 1, not 366!

请注意,Period :: getDays会做一些不同的事情:对于一年和一天的期间,Period :: getDays将返回1,而不是366!

#2


2  

Use LocalDate and Period:

使用LocalDate和Period:

LocalDate d1 = LocalDate.of(2017, 05, 01);
LocalDate d2 = LocalDate.of(2017, 05, 18);


System.out.println(ChronoUnit.DAYS.between(d1, d2));

you can get the actual date using

你可以使用获得实际的日期

LocalDate d1 = LocalDate.now()

#1


1  

If you have two LocalDates, you can use:

如果您有两个LocalDates,则可以使用:

longs days = ChronoUnit.DAYS.between(date1, date2);

Note that Period::getDays does something different: for a period of one year and one day, Period::getDays will return 1, not 366!

请注意,Period :: getDays会做一些不同的事情:对于一年和一天的期间,Period :: getDays将返回1,而不是366!

#2


2  

Use LocalDate and Period:

使用LocalDate和Period:

LocalDate d1 = LocalDate.of(2017, 05, 01);
LocalDate d2 = LocalDate.of(2017, 05, 18);


System.out.println(ChronoUnit.DAYS.between(d1, d2));

you can get the actual date using

你可以使用获得实际的日期

LocalDate d1 = LocalDate.now()