[JAVA] Shows how many years and months the difference from a particular date is

I needed to show the difference between a specific date, which is an in-house system, and the current date in years and months, so I looked it up.

I used java.time which I haven't used much. This time, we don't need time, so we use LocalDate instead of LocalDateTime.

LocalDate sampleDate = LocalDate.parse("2019/12/09", DateTimeFormatter.ofPattern("yyyy/MM/dd"));
LocalDate currentDate = LocalDate.now();
//Get the difference between a specific date and today in year format
//long year = ChronoUnit.YEARS.between(sampleDate , currentDate); 
//Get the difference between a specific date and today in monthly format * Wrong. Get the total number of months
//long month = ChronoUnit.MONTHS.between(sampleDate , currentDate);

//Corrected by the method you commented
Period period = Period.between(sampleDate , currentDate);
//Get the difference between a specific date and today in year format
long year = period.getYears();
//Get the difference between a specific date and today in monthly format
long month = period.getMonths();

The year and month obtained above are displayed on the screen as character strings.

I also used PHP recently, so a memorandum. Since PHP is self-taught, it may be wrong.

$sampleDate = new DateTime('2019/12/09');
$currentDate = new DateTime('now');
$diffDate = $currentDate ->diff($sampleDate);
$year = $diffDate->format('%y');
$month = $diffDate->format('%m');

the end!

Recommended Posts

Shows how many years and months the difference from a particular date is
What is the difference between a class and a struct? ?? ??
How to create a form to select a date from the calendar
What is the difference between a web server and an application server?
Find the difference from a multiple of 10
[Ruby] What is the slice method? Let's solve the example and understand the difference from slice!
What is the difference between SimpleDateFormat and DateTimeFormatter? ??
Is there a performance difference between Oracle JDK and OpenJDK at the end of 2017?
[Java] I want to calculate the difference from the date
What is the difference between System Spec and Feature Spec?
[Rails] What is the difference between redirect and render?
[JAVA] What is the difference between interface and abstract? ?? ??
21 Load the script from a file and execute it
What is the difference between skip and pending? [RSpec]
What is the difference between Java EE and Jakarta EE?
SDWebImage: How to clear the cache for a particular UIImageView
[Rails] What is the difference between bundle install and bundle update?
How to write a migration from Rails datetime type to date type
Difference between Java and JavaScript (how to find the average)
What is the LocalDateTime class? [Java beginner] -Date and time class-
Set the date and time from the character string with POI
What is the difference between an action and an instance method?