how do I subtract 24 hour from date time object in PHP

后端 未结 10 1412
我寻月下人不归
我寻月下人不归 2020-12-17 07:57

I have the following code:

  $now = date(\"Y-m-d H:m:s\");
  $date = date(\"Y-m-d H:m:s\", strtotime(\'-24 hours\', $now));

However, now it

10条回答
  •  星月不相逢
    2020-12-17 08:24

    strtotime() expects a unix timestamp (which is number seconds since Jan 01 1970)

    $date = date("Y-m-d H:i:s", strtotime('-24 hours', time())); ////time() is default so you do not need to specify.
    

    i would suggest using the datetime library though, since it's a more object oriented approach.

    $date = new DateTime(); //date & time of right now. (Like time())
    $date->sub(new DateInterval('P1D')); //subtract period of 1 day
    

    The advantage of this is that you can reuse the DateInterval:

    $date = new DateTime(); //date & time of right now. (Like time())
    $oneDayPeriod = new DateInterval('P1D'); //period of 1 day
    $date->sub($oneDayPeriod);
    $date->sub($oneDayPeriod); //2 days are subtracted.
    $date2 = new DateTime(); 
    $date2->sub($oneDayPeriod); //can use the same period, multiple times.
    

    Carbon (update 2020)

    Most popular library for processing DateTimes in PHP is Carbon.

    Here you would simply do:

    $yesterday = Carbon::now()->subDay();
    

提交回复
热议问题