用 PHP 减去天数

Roshan Parmar 2023年1月30日
  1. 在 PHP 中使用 strtotime() 方法减去天数
  2. 在 PHP 中使用 DateTime() 减去天数
  3. 从 PHP 中的给定日期中减去
  4. 从 PHP 中的给定日期减去星期
用 PHP 减去天数

这是从 PHP 中的给定日期减去天、周或月的重要方法。像我们这样的方法可以使用 PHP 的 strtotime 方法或内置的 DateTime 类来完成。

date()strtotime() 两个函数都在 PHP 中使用。这使得从给定日期或当前时间(日期)中减去时间(小时、分钟和秒)变得简单。

date() 方法在格式化特定时间后返回一个准备好的字符串。

另一方面,将格式化为 DateTime 的文本转换为 Unix 时间戳。date()strtotime() 可以帮助从 PHP 中的当前时间(日期)中减去时间。

因此,这是从当前 DateTime 中减去时间的方法。用 PHP 表格当前日期减去 1 天:

在 PHP 中使用 strtotime() 方法减去天数

示例代码:

<?php
// current time in PHP
$datetime = date("Y-m-d ");
// print current time
echo $datetime;
echo "\n";
//After using of strotime fuction then result 
$yesterday = date("Y-m-d", strtotime("yesterday"));
echo $yesterday;
?>

输出:

2021-12-06
2021-12-05

上面是通过将字符串昨天提供给 strtotime 从当前日期减去天数的示例。

在 PHP 中使用 DateTime() 减去天数

示例代码:

<?php
//New DateTime object representing current date.
$currentDate = new DateTime();
 
 
//Use the subtract function to subtract a DateInterval
$yesterdayTime = $currentDate->sub(new DateInterval('P1D'));
 
//Get yesterday date
$yesterday = $yesterdayTime->format('Y-m-d');
 
//Print yesterday date.
echo $yesterday;
?>

输出:

2021-12-05

我们使用 DateInterval 类讨论了 PHP 的旧版本 5.3.0。它代表一个日期期间。

现在,我们将讨论 P1D。我们将 DateInterval 类的对象定义为 P1D,这意味着一天(一天的周期)。

间隔可以从给定的日期和时间中扣除。如果你想删除五天而不是一天,我们可以使用 P5D(五天)而不是 P1D(一天)。

从 PHP 中的给定日期中减去

示例代码:

<?php
//Pass the date which  you want to subtract from
//the $time parameter for DateTime.
$currentDate = new DateTime('2021-01-01');
 
//Subtract a day using DateInterval
$yesterdayTime = $currentDate->sub(new DateInterval('P1D'));
 
//Get the date in a YYYY-MM-DD format.
$yesterday = $yesterdayTime->format('Y-m-d');
//Print Date.
echo $yesterday;
?>

输出:

2020-12-31

从 PHP 中的给定日期减去星期

使用 strtotime()

示例代码:

<?php
 
//One week or 7 days ago
$lastWeekDate = date("Y-m-d", strtotime("-7 days"));
 
//OutPut
echo $lastWeekDate;
?>

输出:

2021-11-29

正如我们所知,从 start time() 方法开始,我们可以从给定的日期中减去时间、日、月和年。

P1W$interval 规范参数 DateInterval 类。它代表一周的时间,P1W= 一周周期。现在,如果你想将 P1W(一周期限)更改为 P2W 以扣除两周,这将是一个很好的方法。

相关文章 - PHP DateTime