LoginSignup
17
18

More than 5 years have passed since last update.

[#php]年度を取得する関数

Last updated at Posted at 2015-12-25

htmlで書かれてた古いサイト(Expressで編集されてたらしい)を
部分的に.phpに直して自動更新できるように直していってます。

その過程で、年度を取得できると嬉しいので実装しました。

/**
 * @input: start_date, the start date of a fiscal year
 * @output: fiscal year
 */
function getFiscalYearOfToday($start_date='04/01'){
  $today = date('Y/m/d');
  $start_year = date('Y').'/'.$start_date;// 2015/04/01 or 2016/04/01
  if(strtotime($today) >= strtotime($start_year)){
    // e.g. 2015.4.1 ~ 2015.12.31 => 2015
    $year = date('Y');
  }else{
    // e.g. 2016.01.01 ~ 2016.03.31 => 2015
    $year = date('Y') - 1;
  }
  return $year;
}

デフォルト値で4月1日を入れていて、その日より前か後かで年度を取得します。
これでまた少しヘルシーになった。

Thanks to 【PHP】日付比較 - Qiita

追記(2017/03/18)

コメントに頂いている通り、大幅にコードを短くすることが可能で、下記の1個めの方がそれに相当します。
しかし、VM上でCentOS7, php5.4.16ではうまく実行されず、2個めを書くことにしました。

echo (new \DateTime('-3 month'))->format('Y');# 1個め
echo date('Y', strtotime('-3 month'));# 2個め
17
18
4

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
17
18