php教程

date_sub

(PHP 5 >= 5.3.0, PHP 7)

date_sub别名 DateTime::sub()

说明

此函数是该函数的别名: DateTime::sub()

User Contributed Notes

fpradove at gmail dot com 07-Apr-2018 12:05
In version 5.6.31 the variable $ today is passed by reference in the function date_sub () and the interval is also applied

<?php
$today
= date_create(date('Y-m-d'));
$yesterday = date_sub($today, date_interval_create_from_date_string("1 days"));

        echo
var_dump($today);
        echo
var_dump($yesterday)
?>
vitkor dot kruglikov at gmail dot com 15-Jun-2015 08:55
It can be unclear for someone how to use this function.
Here is the example:

$date=date_create("2013-03-15");
date_sub($date,date_interval_create_from_date_string("40 days"));
echo date_format($date,"Y-m-d");
Thomas LEDUC 04-Feb-2015 11:14
To glue to the OOP, it's better to use it with DateInterval::createFromDateString

<?php
$dateB
= new DateTime('2020-12-20');
$dateA = $dateB->sub(DateInterval::createFromDateString('10 days'));
?>

more detail here :
<?php
public static function createFromDateString ($time) {}
?>
Jonathan Poissant 21-Jan-2011 07:26
You cannot replace date_sub('2000-01-20') by DateTime::sub('2000-01-20') because DateTime::sub is not static. You have to create the DateTime object first.

Example:

<?php $dateA = date_sub('2000-01-20', date_interval_create_from_date_string('10 days')); ?>

will be replace by
<?php
$dateB
= new DateTime('2000-01-20');
$dateA = $dateB->sub(date_interval_create_from_date_string('10 days'));
?>

CopyRight © 2008-2022 verySource.Com All Rights reserved. 京ICP备17048824号-1 京公网安备:11010502034788