LoginSignup
0
0

More than 5 years have passed since last update.

先月の日時を求める関数

Last updated at Posted at 2017-06-01

目的

先月の日時を得たいが、単純に月を1引いた日時が存在し得ない暦になってしまう場合は、先月の末日に直してから得たい。

コード

php

<?php

function getPrevMonthDatetime($datetime)
{
    // 先月の1日のtime
    $prevFirstTime = strtotime(date('Y-m-01 00:00:00', strtotime($datetime)).' -1 month');
    // 先月の年
    $prevYear    = date('Y', $prevFirstTime);
    // 先月の月
    $prevMonth   = date('m', $prevFirstTime);
    // 先月の末日
    $prevLastDay = date('t', $prevFirstTime);

    $nowTime = strtotime($datetime);
    // 現在の日
    $nowDay = date('d', $nowTime);
    // 現在の時分秒
    $nowHis = date('H:i:s', $nowTime);

    // もし現在の日より先月の末日が前なら、先月の末日になる
    if ($prevLastDay < $nowDay) {
        return $prevYear.'-'.$prevMonth.'-'.$prevLastDay.' '.$nowHis;
    }

    // そうでなければ、先月の現在の日になる
    return $prevYear.'-'.$prevMonth.'-'.$nowDay.' '.$nowHis;
}

テスト

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