10
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

phpで時刻使うならDateTime使いましょう

Last updated at Posted at 2016-02-26

php5.2以上ならDateTimeが使えるのでDateTime使いましょう。date()よりは便利です。

基本ここにまとめてある
http://qiita.com/re-24/items/c3ed814f2e1ee0f8e811

かるく補足

任意の日時を作成(現在を基準に1日前とかやりたい場合)

$date1 = new DateTime(); // 20160101-00:00:00
$date2 = new DateTime('+1 days'); // 20160102-00:00:00
$date3 = new DateTime('-1 days'); // 20151231-00:00:00
$date4 = new DateTime('+1 weeks'); // 20160108-00:00:00
$date5 = new DateTime('+1 month'); // 20160201-00:00:00
$date6 = new DateTime('+1 hours'); // 20160101-01:00:00
$date7 = new DateTime('+1 mins'); // 20160101-00:01:00
$date8 = new DateTime('+1 seconds'); // 20160101-00:00:01

時間の比較

$date1 = new DateTime();
$date1_ = new DateTime();
$date3 = new DateTime('-1 days');

if($date1 == $date1_) {
    echo 'ok';
};

if($date1 > $date3) {
    echo 'ok';
};

任意の時間を指定(実行日の9時とか、実行日の3日前の9時とか)

// create_date('today')で実行日の0時0分がとれる
$this_9 = date_create('today')->modify('+9 hours'); 

// create_date('today')で実行日の0時0分がとれる
// 3日前に戻した後、9時間増やす
$this_9 = date_create('today')->modify('-3 days')->modify('+9 hours'); 


10
12
1

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
10
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?