php - 如何从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
$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
推荐阅读
- eclipse - 无法通过 Eclipse 向导创建 hibernate.cfg.xml?
- python - 如何从python中的矩阵中选择每列中最小值最多的行?
- postgresql - PostgREST / PostgreSQL 无法扩大字符串缓冲区消息
- python - 在 Colab 中访问公共 Google 驱动器文件夹(不是来自我的驱动器)?
- python - 未定义的字母变量在 Python 中有效
- vb.net - 如何在从网站提取数据时修复“Windows 安全警告”弹出问题
- reactjs - React 组件状态和 API 获取
- c# - Golang 使用 AES 加密数据
- python - 如何使用 Python 将 turle RDF (ttl) 数据导入 neo4j?当前的ttl文件包含本体数据
- javascript - 为什么我的不和谐机器人忽略 awaitMessages?