DateTimeImmutable::sub()函数是PHP中的内置函数,用于从创建的DateTimeImmutable对象中减去若干天,几个月,几年,几小时和几秒钟。
用法:
DateTimeImmutable::sub( interval )
参数:此函数接受参数间隔,该间隔是要从给定的DateTimeImmutable对象中减去的天数或月数或年数或小时数或分钟数或秒数。
返回值::此函数在减去后返回最终的日期时间。
以下示例程序旨在说明DateTimeImmutable::sub()函数:
程序1::此程序将天数减少2。
// PHP program to illustrate DateTimeImmutable::sub()
// function
// Creating a new DateTimeImmutable() object
$datetimeImmutable = new DateTimeImmutable('2019-10-07');
// Initialising a interval of 2 days
$interval = 'P2D';
// Calling the DateTimeImmutable::sub() function
$a = $datetimeImmutable->sub(new DateInterval($interval));
// Getting a new date time
// format of 'Y-m-d'
echo $a->format('Y-m-d');
?>
输出:
2019-10-05
程序2::此程序将月份减少5。
// PHP program to illustrate DateTimeImmutable::sub()
// function
// Creating a new DateTimeImmutable() object
$datetimeImmutable = new DateTimeImmutable('2019-10-07');
// Initialising a interval of 5 months
$interval = 'P5M';
// Calling the DateTimeImmutable::sub() function
$a = $datetimeImmutable->sub(new DateInterval($interval));
// Getting a new date time
// format of 'Y-m-d'
echo $a->format('Y-m-d');
?>
输出:
2019-05-07
参考