如何从php中的日期编号中获取上一个和下一个日期



我想在一个月的日期范围内查找条目

就像用户在一个月的20号注册一样,脚本应该获得从上一个月20号到下一个月二十号的条目。

也就是说,如果脚本在4月20日之前的任何一天运行,则范围应为3月20日至4月20号,如果脚本运行在4月二十日或之后,则范围应该为4月20至5月20日。

我查找了相对格式,但它只列出了日期和星期等的函数。

相对日期格式有没有办法像上一个n到下一个n一样工作,其中n=1到31。

有人能帮忙吗?感谢

根据Cully的评论,这里有一个实现(它仍然感觉太混乱,也许有一种更容易的方法(。这可能会进一步解释这个问题。

function getFromDate($myDate, $nDate)
{
// sub 1 day till date is $nDate
while(true)
{
if($myDate->format('d')==$nDate)
break;
$myDate->sub(new DateInterval('P1D'));
}
return $myDate;
}
function getToDate($myDate, $nDate)
{
// add 1 day till date is $nDate
while(true)
{
$myDate->add(new DateInterval('P1D'));
if($myDate->format('d')==$nDate)
break;
}
return $myDate;
}
$timestamp = 1602107066; // An example user registration date, 7 October 2021
$nDate = gmdate("d", $timestamp);
$fromDate = getFromDate(new DateTime('now'), $nDate);
$toDate = getToDate(new DateTime('now'), $nDate);
echo $fromDate->format('d M y')."rn"; // 7 May 2021 (run on May 22 2021)
echo $toDate->format('d M y'); // 7 June 2021 (run on May 22 2021)

你的意思是这样的吗?它可能不是你想要的,但你能用它来创造你想要的吗?

<?php
$numberOfDaysIWant = 20;
// March 20th, 2021, but you can use any date you want
$startDate = new DateTimeImmutable('2021-03-20');
$myPastDates = [];
$myFutureDates = [];
$currentDate = $startDate;
for($i = 0; $i < $numberOfDaysIWant; $i++) {
$currentDate = $currentDate->sub('P1D');
$myPastDates []= $currentDate;
}
$currentDate = $startDate;
for($i = 0; $i < $numberOfDaysIWant; $i++) {
$currentDate = $currentDate->add('P1D');
$myFutureDates []= $currentDate;
}
var_dump($myPastDates, $myFutureDates);

从你的问题中还不清楚,但听起来你可能想根据所选月份的日期获得$numberOfDaysIWant值。如果是这样的话,你可以用这个来获得它:

<?php
$startDate = new DateTimeImmutable('2021-03-20');
$numberOfDaysIWant = (int) $startDate->format('j'); // "j" gives you the day of the month, without leading zeroes

最新更新