社内システムである特定の日付と現在の日付との差を何年何か月で表示する必要があったので、調べてみた。
- Java
あまり使ってこなかった java.time を使用。
今回は時間までは必要ないため、LocalDateTimeではなく、LocalDateを使用。
LocalDate sampleDate = LocalDate.parse("2019/12/09", DateTimeFormatter.ofPattern("yyyy/MM/dd"));
LocalDate currentDate = LocalDate.now();
// 特定の日付と本日の差を年形式で取得
//long year = ChronoUnit.YEARS.between(sampleDate , currentDate);
// 特定の日付と本日の差を月形式で取得 ※間違い。トータル月数が取得される
//long month = ChronoUnit.MONTHS.between(sampleDate , currentDate);
// コメントいただいた方法で修正
Period period = Period.between(sampleDate , currentDate);
// 特定の日付と本日の差を年形式で取得
long year = period.getYears();
// 特定の日付と本日の差を月形式で取得
long month = period.getMonths();
上記で取得した年と月を文字列にして画面に表示。
- PHP
ついでにPHPも最近使ったので覚書。
PHPは独学なのでやり方間違っているかも。
$sampleDate = new DateTime('2019/12/09');
$currentDate = new DateTime('now');
$diffDate = $currentDate ->diff($sampleDate);
$year = $diffDate->format('%y');
$month = $diffDate->format('%m');
終わり!