首页 > 解决方案 > 如何从php中的日期编号获取最后一个日期和下一个日期?

问题描述

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

就像用户在一个月的 20 日注册一样,脚本应该获取从该月的最后 20 日到下一个 20 日的范围内的条目。

即,如果脚本在 4 月 20 日之前的任何一天运行,则范围应该是 3 月 20 日 - 4 月 20 日,如果它在 4 月 20 日或之后运行,那么范围应该是 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')."\r\n"; // 7 May 2021 (run on May 22 2021)
echo $toDate->format('d M y'); // 7 June 2021 (run on May 22 2021)

标签: php

解决方案


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

<?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

推荐阅读