Java Reference
In-Depth Information
Discussion
Given two LocalDate objects, you can find the difference between them, as a Period ,
simply using the static Period.between() method. You can toString() the Period or, if
its default format isn't good enough, format the result yourself:
import
import java.time.LocalDate
java.time.LocalDate ;
import
import java.time.Period
java.time.Period ;
public
public class
class DateDiff
DateDiff {
public
public static
void main ( String [] args ) {
/** The date at the end of the last century */
LocalDate endofCentury = LocalDate . of ( 2000 , 12 , 31 );
LocalDate now = LocalDate . now ();
static void
Period diff = Period . between ( endofCentury , now );
System . out . printf ( "The 21st century (up to %s) is %s old%n" , now , diff );
System . out . printf (
"The 21st century is %d years, %d months and %d days old" ,
diff . getYears (), diff . getMonths (), diff . getDays ());
}
}
I'm editing this recipe at the end of October 2013; the 20th century A.D. ended at the end of
2000, so the value should be about 12 10 / 12 years, and it is:
$ java datetime.DateDiff
The 21st century (up to 2013-10-28) is P12Y9M28D old
The 21st century is 12 years, 9 months and 28 days old
Because of the API's regularity, you can use the same technique with LocalTime or
LocalDateTime .
See Also
A higher-level way of formatting date/time values is discussed in Formatting Dates and
Times .
Search WWH ::




Custom Search