用PHP减去1天

我试图从我的Drupal CMS取出date对象,减去一天并打印出两个date。 这是我的

$date_raw = $messagenode->field_message_date[0]['value']; print($date_raw); //this gives me the following string: 2011-04-24T00:00:00 $date_object = date_create($date_raw); $next_date_object = date_modify($date_object,'-1 day'); print('First Date ' . date_format($date_object,'Ym-d')); //this gives me the correctly formatted string '2011-04-24' print('Next Date ' . date_format($next_date_object,'Ym-d')); //this gives me nothing. The output here is always blank 

所以我不明白为什么原来的date对象出来,但我试图创build一个额外的date对象,并通过减去一天来修改它,似乎我不能这样做。 输出总是空白。

你可以试试:

 print('Next Date ' . date('Ym-d', strtotime('-1 day', strtotime($date_raw)))); 
  date('Ym-d',(strtotime ( '-1 day' , strtotime ( $date) ) )); 

面向对象的版本

 $dateObject = new DateTime( $date_raw ); print('Next Date ' . $dateObject->sub( new DateInterval('P1D') )->format('Ym-d'); 

不知道为什么你当前的代码不工作,但如果你不特别需要一个date对象,这将工作:

 $first_date = strtotime($date_raw); $second_date = strtotime('-1 day', $first_date); print 'First Date ' . date('Ym-d', $first_date); print 'Next Date ' . date('Ym-d', $second_date); 
 $date = new DateTime("2017-05-18"); // For today/now, don't pass an arg. $date->modify("-1 day"); echo $date->format("Ymd H:i:s"); 

使用date时间显着减less了在操纵date时忍受的头痛的数量。

怎么样:首先将它转换为unix时间戳,然后减去60 * 60 * 24(正好是一秒钟),然后从中获取date。

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

注意:正如apokryfos所指出的那样,这在技术上会被夏时制的变化所抛弃,那里将会有25或23个小时

单行选项是:

 echo date_create('2011-04-24')->modify('-1 days')->format('Ym-d'); 

在在线PHP编辑器上运行它。


mktime替代

如果您更喜欢避免使用string方法或进行计算,甚至创build其他variables,则mktime按以下方式支持减法和负值:

 // Today's date echo date('Ym-d'); // 2016-03-22 // Yesterday's date echo date('Ym-d', mktime(0, 0, 0, date("m"), date("d")-1, date("Y"))); // 2016-03-21 // 42 days ago echo date('Ym-d', mktime(0, 0, 0, date("m"), date("d")-42, date("Y"))); // 2016-02-09 //Using a previous date object $date_object = new DateTime('2011-04-24'); echo date('Ym-d', mktime(0, 0, 0, $date_object->format("m"), $date_object->format("d")-1, $date_object->format("Y") ) ); // 2011-04-23 

在线PHP编辑器