【问题标题】:Trouble with dates in phpphp中的日期问题
【发布时间】:2020-09-24 20:32:48
【问题描述】:

我想从用户选择的日期开始每三个月打印一次日期,从用户选择的日期开始,但是当我进行增量时,循环中断并且只打印第一个日期,可以帮助我,请

这是我的 PHP 代码

$fecha = date('m/d/Y',strtotime($_POST['fecha']));
printf( date('d/m/Y',strtotime($fecha)).'----');
$fin = date('m/d/Y',strtotime($fecha."+ 1 year"));
printf(date('d/m/Y',strtotime($fin)).'----');
if($fecha<$fin){
    $fecha = date('m/d/Y',strtotime($fecha."+ 1 month"));
    printf( date('d/m/Y',strtotime($fecha)));
}
<form method="POST" action="./fechas.php">
<input type="date" name="fecha" id="fecha">
<input type="submit" value="enviar">
</form>

这是输出:

我想打印这个:

15/10/2020---- 15/11/2020---- 15/12/2020--- ...

【问题讨论】:

  • 您想打印每年最后 3 个月的日期吗?如果用户可以选择不起作用的日期,假设他们从 10 月 31 日开始,那么 11 月只有 30 天。
  • 不,我想每 X 个月打印一次特定日期,例如,如果我选择 2020 年 9 月 15 日,我想打印:2020 年 12 月 15 日、2020 年 3 月 15 日、2020 年 6 月 15 日最后是 2020 年 9 月 15 日。

标签: php html date


【解决方案1】:

当有一个完整的 DateTime 库可以让您的生活更轻松时,您会反复使用最不可靠的函数重新格式化和重新解析日期和时间间隔。

$input = new DateTime('2020-09-24', new DatetimeZone('UTC'));
$past = (clone $input)->sub(new DateInterval('P1Y'));
$period = new DateInterval('P3M');

$cur = clone $past;
do {
    echo $cur->format('Y-m-d') . "\n";
    $cur->add($period);
} while( $cur <= $input );

输出:

2019-09-24
2019-12-24
2020-03-24
2020-06-24
2020-09-24

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-04
    • 1970-01-01
    相关资源
    最近更新 更多