Subtract 1 day with PHP

后端 未结 10 729
我在风中等你
我在风中等你 2020-11-28 06:52

I\'m trying to take a date object that\'s coming out of my Drupal CMS, subtract one day and print out both dates. Here\'s what I have

$date_raw = $messageno         


        
相关标签:
10条回答
  • 2020-11-28 07:16

    How about this: convert it to a unix timestamp first, subtract 60*60*24 (exactly one day in seconds), and then grab the date from that.

    $newDate = strtotime($date_raw) - 60*60*24;
    echo date('Y-m-d',$newDate);
    

    Note: as apokryfos has pointed out, this would technically be thrown off by daylight savings time changes where there would be a day with either 25 or 23 hours

    0 讨论(0)
  • 2020-11-28 07:17

    Simple like that:

    date("Y-m-d", strtotime("-1 day"));

    date("Y-m-d", strtotime("-1 months"))

    0 讨论(0)
  • 2020-11-28 07:21
    $date = new DateTime("2017-05-18"); // For today/now, don't pass an arg.
    $date->modify("-1 day");
    echo $date->format("Y-m-d H:i:s");
    

    Using DateTime has significantly reduced the amount of headaches endured whilst manipulating dates.

    0 讨论(0)
  • 2020-11-28 07:21

    Not sure why your current code isn't working but if you don't specifically need a date object this will work:

    $first_date = strtotime($date_raw);
    $second_date = strtotime('-1 day', $first_date);
    
    print 'First Date ' . date('Y-m-d', $first_date);
    print 'Next Date ' . date('Y-m-d', $second_date);
    
    0 讨论(0)
  • 2020-11-28 07:22

    Object oriented version

    $dateObject = new DateTime( $date_raw );
    print('Next Date ' . $dateObject->sub( new DateInterval('P1D') )->format('Y-m-d');
    
    0 讨论(0)
  • 2020-11-28 07:23

    You can try:

    print('Next Date ' . date('Y-m-d', strtotime('-1 day', strtotime($date_raw))));
    
    0 讨论(0)
提交回复
热议问题