LoginSignup
13
14

More than 5 years have passed since last update.

会計年度を算出するTIPS

Last updated at Posted at 2015-07-09

業務アプリケーションを製作していると、結構な頻度で需要があるので書き慣れているのですが、うっかりミスもよくやってしまうので、メモ。

前提条件

以下のようにテーブル(company)で決算月を永続化している。
会社ID: 1 は 決算月が3月であるという意味です。

company_id closing_month
1 3

SQLで算出する

以下のSQLで現在時点での、会計年度が求められる。
基本的には、年月日から決算月を引けばいいが、12月決算の場合は引いてはいけない。12の剰余を割り出せば望みの結果が得られる。

SELECT 
    `company_id`
    , `closing_month` 
    , YEAR(ADDDATE(NOW(), INTERVAL -1 * (`closing_month` % 12) MONTH)) as `fiscal_year`
FROM company

PHPで算出する

同様に、基準日から決算月を引き、「年」を取り出すことで算出できる。

/**
 * 会計年度を取得する
 * @param $closingMonth 決算月
 * @param $date 基準日 YYYY-MM-DD
 * @return 会計年度 YYYY
 */
function getFiscalYear($closingMonth, $date = 'now')
{
    $objDate = new DateTime($date);
    $interval = sprintf('P%dM', fmod($closingMonth, 12));
    $objDate->sub(new DateInterval($interval));
    return $objDate->format('Y');
}
13
14
0

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
13
14