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