PHP date_sub()函数用法详细介绍

2021年3月16日15:20:49 发表评论 595 次浏览

date_sub()是PHP中的内置函数, 用于从给定日期减去几天, 几个月, 几年, 几小时, 几分钟和几秒钟。该函数在成功时返回DateTime对象, 在失败时返回FALSE。

语法如下:

date_sub($object, $interval)

参数:date_sub()函数接受两个参数, 如下所述:

  • $ object:它是一个强制性参数, 用于指定由返回的DateTime对象。date_create()
  • $ interval:它是一个必需参数, 用于指定要减去的DateInterval对象。

返回值:减去间隔后, 它将返回DateTime对象。

下面的程序说明了date_sub()函数:

程序1:

<?php
// PHP program to illustrate date_sub() function
  
// Subtract 5 years from the 25th of June, 2018
$date = date_create( '2018-06-25' );
date_sub( $date , date_interval_create_from_date_string( '5 years' ));
  
echo date_format( $date , 'Y-m-d' ) . "\n" ;
  
  
// Subtract 5 month from the 25th of June, 2018
$date = date_create( '2018-06-25' );
date_sub( $date , date_interval_create_from_date_string( '5 month' ));
  
echo date_format( $date , 'Y-m-d' ). "\n" ;
  
// // Subtract 5 days from the 25th of June, 2018
$date = date_create( '2018-06-25' );
date_sub( $date , date_interval_create_from_date_string( '5 days' ));
  
echo date_format( $date , 'Y-m-d' );
  
?>

输出如下:

2013-06-25
2013-01-25
2013-01-20

程式2:当传递了无效的日期时, date_sub函数会发出警告:

<?php
// PHP program to illustrate date_sub function
  
// date_sub function gives warning when
// we passing invalid date
$date = date_create( '2018-25-25' );
  
date_sub( $date , date_interval_create_from_date_string( '5 years' ));
  
echo date_format( $date , 'Y-m-d' ) . "\n" ;
?>

输出如下:

PHP Warning: date_sub() expects parameter 1 to be DateTime, boolean given in/home /2662efc623a406b7cb06a7320e7abf50.php on line 8
PHP Warning: date_format() expects parameter 1 to be DateTimeInterface, boolean given in/home/2662efc623a406b7cb06a7320e7abf50.php on line 9

参考: http://php.net/manual/en/function.date-sub.php


木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: