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

后端 未结 10 1362
我寻月下人不归
我寻月下人不归 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();
    
    0 讨论(0)
  • 2020-12-17 08:25
    $date = (new \DateTime())->modify('-24 hours');
    

    or

    $date = (new \DateTime())->modify('-1 day');
    

    (The latter takes into account this comment as it is a valid point.)

    Should work fine for you here. See http://PHP.net/datetime

    $date will be an instance of DateTime, a real DateTime object.

    0 讨论(0)
  • 2020-12-17 08:25

    In same code use strtotime() its working.

    $now = date("Y-m-d H:i:s");
    $date = date("Y-m-d H:i:s", strtotime('-2 hours', strtotime($now)));
    
    0 讨论(0)
  • 2020-12-17 08:27

    all you have to do is to alter your code to be

    $now = strtotime(date("Y-m-d H:m:s"));
    $date = date("Y-m-d H:m:s", strtotime('-24 hours', $now));
    
    0 讨论(0)
提交回复
热议问题