Created
September 3, 2013 19:17
-
-
Save aoitaku/6428318 to your computer and use it in GitHub Desktop.
DateTimeを拡張したTimepiece(時計)クラス
とりあえず下書きのみ
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
date_default_timezone_set('Asia/Tokyo'); | |
/* | |
* 「時計」クラス | |
*/ | |
class Timepiece extends DateTime { | |
static protected $default_format_string = 'Y-m-d H:i:s'; | |
protected $format_string = false; | |
/* | |
* デフォルトのフォーマット文字列を設定する | |
*/ | |
public function set_default_format_string($format_string) { | |
self::$default_format_string = $format_string; | |
} | |
/* | |
* デフォルトのフォーマット文字列を取得する | |
*/ | |
public function default_format_string() { | |
return self::$default_format_string; | |
} | |
/* | |
* フォーマット文字列を設定する | |
*/ | |
public function set_format_string($format_string) { | |
$this->format_string = $format_string; | |
} | |
/* | |
* フォーマット文字列を取得する | |
* 未設定の場合はデフォルトのフォーマット文字列を取得する | |
*/ | |
public function format_string() { | |
if (!$this->format_string) { | |
return $this->default_format_string(); | |
} | |
return $this->format_string; | |
} | |
/* | |
* 文字列への暗黙的キャスト | |
*/ | |
public function __toString() { | |
return $this->format($this->format_string()); | |
} | |
/* | |
* 年を取得する | |
*/ | |
public function year() { return (int)$this->format('Y'); } | |
/* | |
* 月を取得する | |
*/ | |
public function month() { return (int)$this->format('n'); } | |
/* | |
* 日を取得する | |
*/ | |
public function day() { return (int)$this->format('j'); } | |
/* | |
* 当月の日数を取得する | |
*/ | |
static public function days_in_month($time) { | |
return $time->modify('last day of this month')->day(); | |
} | |
/* | |
* 月を加算する | |
*/ | |
public function forward_month($add=1) { | |
$year = $this->year(); | |
$month = $this->month(); | |
$day = $this->day(); | |
$month += $add; | |
if ($month > 12) { | |
$year += (int)floor($month / 12); | |
$month = $month % 12; | |
} | |
$last_day = $this->days_in_month(new Timepiece("{$year}-{$month}-1")); | |
if ($last_day < $day) { | |
$this->setDate($year, $month, $last_day); | |
} else { | |
$this->add(new DateInterval("P{$add}M")); | |
} | |
return $this; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment