0
0

More than 3 years have passed since last update.

特定の日付との差が何年何か月かを表示

Last updated at Posted at 2019-12-15

社内システムである特定の日付と現在の日付との差を何年何か月で表示する必要があったので、調べてみた。

  • 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');

終わり!

0
0
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0