date_sub()是PHP中的一个内置函数,用于从给定日期中减去一些天、月、年、小时、分钟和秒。函数成功时返回DateTime对象,失败时返回FALSE。
null
语法:
date_sub($object, $interval)
参数: date_sub()函数接受两个参数,如下所述:
- $object: 它是一个强制参数,用于指定 创建日期()
- $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' ) . "" ; // 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' ). "" ; // // 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_子函数会发出警告:
<?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' ) . "" ; ?> |
输出 :
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, booleangiven in/home/2662efc623a406b7cb06a7320e7abf50.php on line 9
参考: http://php.net/manual/en/function.date-sub.php
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END