【问题标题】:get current day in next 12 months获取未来 12 个月的当前日期
【发布时间】:2014-05-12 02:52:56
【问题描述】:

是否有可能在未来 12 个月内获得当前日期?

看看这些场景:

Today is 2014-05-09
next month will be 2014-06-09
and so on and so fourth

what if today is 2014-01-31
next month is 2014-02-28

Other examples
what if today is 2014-05-31
next month will be 2014-06-30

谢谢

【问题讨论】:

  • 可以做任何事情。你愿意把问题说得更具体一点吗?
  • “下个月的一天”的模式并不完全清楚。你的意思是“一个月后”? “三十天后?”还有什么?
  • 我将更新我的问题。
  • 如果您在 30 天后需要,那么您应该访问此链接,您可以在这里找到一些提示stackoverflow.com/questions/14584115/…
  • @phphopzter 检查我的答案

标签: php date


【解决方案1】:

试试这个。即使日期也是本月的最后一天,它也能正常工作

$date = "2013-03-31";

$d1 = explode("-",$date);

$i = 0;

while ($i < 12)
{

$j = $d1[2];

if(cal_days_in_month(CAL_GREGORIAN, $d1[1], $d1[0]) < $d1[2])
$j = cal_days_in_month(CAL_GREGORIAN, $d1[1], $d1[0]) ;

echo $d1[0]."-".$d1[1]."-".$j."<br>";

$d1[1]++;

if($d1[1] == 13)
{
$d1[0]++;
$d1[1] = 1;
}
$i++;

if($d1[1] < 10)
$d1[1]="0".$d1[1];

}

【讨论】:

  • 注意: 日期格式应为Y-m-d
  • @phphopzter 将 if($d1[1] == 12) 更改为 if($d1[1] == 13)
【解决方案2】:

您可以将 DateInterval 添加到给定日期。但是您的示例中没有统一的逻辑。

例如:

$date = new DateTime( '2014-01-31' );
$aMonthLater = clone $date;
$aMonthLater->add( new DateInterval( 'P1M' ) );


var_dump(
    $date->format( DateTime::ISO8601 ),
    $aMonthLater->format( DateTime::ISO8601 )
);

这将导致如下输出:

2014-01-31T00:00:00+01:00
2014-03-03T00:00:00+01:00

因此,添加一个月实际上会添加一整月 - 您的示例(从 2014 年 1 月 31 日跳过到 2014 年 2 月 28 日)不会添加一整月。

DateTime::add()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-06
    • 2015-08-16
    • 2012-01-07
    • 1970-01-01
    • 2021-08-12
    • 1970-01-01
    • 1970-01-01
    • 2022-01-24
    相关资源
    最近更新 更多