LoginSignup
0
0

More than 5 years have passed since last update.

PEACH ライブラリで月末・月初の処理

Posted at

【PHP】月末・月初の出力方法 の内容を PEACH ライブラリで書いてみました.

導入

  1. http://trashtoy.github.io/peach/ から最新版 (2013-06-06 時点で ver 0.1.0) をダウンロードします.
  2. ZIP ファイルを展開し, src ディレクトリを適当なディレクトリに配置します.
  3. PHP ファイルで以下のように autoload.php を読み込みます. (または SplClassLoader などを利用して手動で autoload の設定をしてください)
<?php
require_once("/path/to/peach/src/autoload.php");

// Your code here...

コード例

今月はじめの日付

「日」のフィールドに 1 をセットします.

<?php
$today = Peach_DT_Date::now();
$first = $today->set("date", 1);
echo $first; // "2013-06-01"

前月末の日付

「日」のフィールドに 0 をセットするのが一番簡単です. 「今月 1 日の前日」という風に考えると分かりやすいと思います.

<?php
$today = Peach_DT_Date::now();
$prev  = $today->set("date", 0);
echo $prev; // "2013-05-31"

前月はじめの日付

「日」のフィールドに 1 をセットしてから「月」のフィールドを 1 減らします.

<?php
$today = Peach_DT_Date::now();
$prev  = $today->set("date", 1)->add("month", -1);
echo $prev; // "2013-05-01"

この順番は重要です. もしも「月」を先に操作してしまった場合, 今日が仮に 7 月 31 日とすると, 月を 1 減らした時点で

  1. 2013-07-31
  2. 2013-06-31 (月の値を 1 減らす)
  3. 2013-07-01 (6/30 の翌日ということで自動的に変換される)

という具合に内部状態が変化するため, 期待する結果が得られません.

以下のように setAll を使う方法もあります. コチラはすべてのフィールドを同時に更新するので上のような問題は起きません.
慣れないうちは, 複雑な操作を行う場合に setAll を使うことをオススメします.

<?php
$today     = Peach_DT_Date::now();
$lastMonth = $today->get("month") - 1;
$prev      = $today->setAll(array("month" => $lastMonth, "date" => 1));
echo $prev; // "2013-05-01"

今月末の日付

正攻法で書くと、こんな感じです.

<?php
$today = Peach_DT_Date::now();
$last  = $today->set("date", $today->getDateCount());
echo $last; // "2013-06-30"

または「来月の 1 日の前日」という考え方で記述することもできます.

<?php
$today = Peach_DT_Date::now();
$last  = $today->set("date", 1)->add("month", 1)->set("date", 0);
echo $last; // "2013-06-30"

翌月はじめの日付

先月はじめの日付と同様の考え方です.

<?php
$today = Peach_DT_Date::now();
$next  = $today->set("date", 1)->add("month", 1);
echo $next; // "2013-07-01"

または

<?php
$today     = Peach_DT_Date::now();
$nextMonth = $today->get("month") + 1;
$next      = $today->setAll(array("month" => $nextMonth, "date" => 1));
echo $next; // "2013-07-01"

さらにこんな書き方も出来ます.

<?php
$today = Peach_DT_Date::now();
$next  = $today->set("date", $today->getDateCount() + 1);
echo $next; // "2013-07-01"

この方法では以下のように内部状態が変化し, 結果的に来月 1 日の日付が取得できます.

  1. 2013-06-06 (今日の日付を取得)
  2. 2013-06-31 (「日」のフィールドに 今月末の日付に +1 したものをセット)
  3. 2013-07-01 (6/30 の翌日ということで自動的に変換される)

詳細について

より詳しい使い方や仕様は http://trashtoy.github.io/peach/li_DT.html にあります.

0
0
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
0
0