LoginSignup
5
2

More than 5 years have passed since last update.

Carbonで'0000-00-00 00:00:00'の時刻を作る

Last updated at Posted at 2015-08-01

きっかけ

cakePHPでsoftDeletePluginを使うとき、削除日のデフォルトを'0000-00-00 00:00:00'にする必要がありました。
ので、Carbonを入れて、'0000-00-00 00:00:00'(のDateTime)を作ってみました。
(MySQLで時刻カラムにnull突っ込むと、'0000-00-00 00:00:00'になることを知る前の話・・・)

やり方

こうだ!

$date = Carbon::create(0, 0, 0, 0);

なんでそうなるか

Carbonのcreateを見てみましょう。

public static function create($year = null, $month = null, $day = null, $hour = null, $minute = null, $second = null, $tz = null)
    {
        $year = ($year === null) ? date('Y') : $year;
        $month = ($month === null) ? date('n') : $month;
        $day = ($day === null) ? date('j') : $day;

        if ($hour === null) {
            $hour = date('G');
            $minute = ($minute === null) ? date('i') : $minute;
            $second = ($second === null) ? date('s') : $second;
        } else {
            $minute = ($minute === null) ? 0 : $minute;
            $second = ($second === null) ? 0 : $second;
        }

        return static::createFromFormat('Y-n-j G:i:s', sprintf('%s-%s-%s %s:%02s:%02s', $year, $month, $day, $hour, $minute, $second), $tz);
    }

\$year、\$month、\$day、\$hourがnullでなかったら、それぞれその値を、さらに\$hourがnullではなく、\$minuteと\$secondがnullの場合は0を使うようになってます。
なので、\$year、\$month、\$day、\$hourに、それぞれ0を渡すと、'0000-00-00 00:00:00'の値を持ったDateTimeができあがるというわけです。
簡単ですね(´・ω・`)b

と思っていたけれど

すみません、嘘つきました。
phpdocにもあるんですけど、'-0001-11-30'になってしまうようです。。。

5
2
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
5
2