タグ別アーカイブ: 日付

日付取得で気をつけておきたい事

タグ: , | 投稿日: 投稿者:

はじめまして、ニタです。

早速ですが、PHPで「今から数日後」「今から数ヶ月後」の日付が欲しい場合、こんな書き方をすると思います。

// 今から2日後
date('Y-m-d H:i:s',strtotime(date('Y-m-d H:i:s',time()) . "+2 days"));

では、以下の条件ではどうでしょうか。


$date = "2012-8-31 00:00:00";
$res = date('Y-m-d H:i:s', strtotime($date . " + 6 month"));
print_r($res);

結果は「2013-03-03 00:00:00」となります。
ですが、8月31日の6ヶ月後なので、2月末日(2013-02-29)でないといけないと思います。

これはstrtotime()において、以下の様に判断しているからのようです。
・2012年8月31日の6ヶ月後は2013年2月31日

・2月31日は存在しない

・31日は28日から3日後。つまり3月3日

最初の時点で日付の正当性をチェックをすべきなのですが、間違ってますね。
なので、ここは多少面倒ですが日付の正当性チェックを挟むようにします。


$sdate = "2012-8-31 00:00:00";
// 年月日時分秒毎に分ける
$hour = date('H',strtotime($sdate));
$min = date('i',strtotime($sdate));
$sec = date('s',strtotime($sdate));
$mon = date('m',strtotime($sdate));
$day = date('d',strtotime($sdate));
$year = date('Y',strtotime($sdate));
// 6ヶ月後の月の1日
$ym = mktime($hour,$min,$sec,$mon + 6,1,$year);
$arrayYm = getdate($ym);
// 日を置き換えて日時の正当性チェック
if(checkdate($arrayYm['mon'],(int)$day,$arrayYm['year'])){
    // そのままの日付で日時取得
    $res = mktime($arrayYm['hours'],$arrayYm['minutes'],$arrayYm['seconds'],$arrayYm['mon'], $day, $arrayYm['year']);
}else{
    // 6ヶ月後の末日にして日時取得
    $res = mktime($arrayYm['hours'],$arrayYm['minutes'],$arrayYm['seconds'],$arrayYm['mon'], date('t', $ym),$arrayYm['year']);
}
print_r(date('Y-m-d H:i:s',$res));

こんな感じで日付の正当性チェックをしつつ日付取得を行うと、いいと思います。