【问题标题】:Get 12 Months Ago In PHP [duplicate]在 PHP 中获取 12 个月前 [重复]
【发布时间】:2017-08-03 13:56:31
【问题描述】:

我正在 php 中捕获当前月份的第一天和最后一天。然后我想更进一步,减去 12 个月,这样我就可以得到 12 个月前和 11 个月前一个月的第一天和最后一天。我的问题是语法永远不会从当前月份改变。以下所有结果均产生 08/01/2017 和 08/31/2017

应该如何改变它才能产生准确的结果?

    $firstdayofmonth = date('Y-m-01');
$lastdayofmonth = date('Y-m-t');

$firstdayofmonth = date('m-d-Y', strtotime($firstdayofmonth));
$lastdayofmonth = date('m-d-Y', strtotime($lastdayofmonth));

$month12start = date($firstdayofmonth, strtotime("-12 months"));
$month12end = date($lastdayofmonth, strtotime("-12 months"));
$month11start = date($firstdayofmonth, strtotime("-11 months"));
$month11end = date($lastdayofmonth, strtotime("-11 months"));

echo $month12start;
echo $month12end;
echo $month11start;
echo $month11end;

【问题讨论】:

  • 您将一个来自 date() 的字符串变量传递给新的 date() 调用的格式参数 - 这没有多大意义。
  • $month12start = date('08-01-2017', strtotime("-12 months")) 没有日期格式字符,您不会得到任何更改。
  • @Qirel - 你会建议我如何设置它?
  • 我是从移动 atm 写的,所以编写代码有点困难 - 但基本上你将日期字符串而不是有效格式传递给 date(),这就是失败的原因。你会得到类似date("08-01-2017") 的东西,它应该是你的前四行。
  • 看看 Carbon 库:carbon.nesbot.com。它具有选择月份的开始和结束,减去月份等方法。

标签: php


【解决方案1】:

strtotime() 不是 PHP 中最可靠的日期方法,并且可能会出现一些奇怪的行为,请参见此处 - Removing exactly one month from a date

我会建议您像这样使用DateTime()

$date = new DateTime(); //Today
$lastDay = $date->format("Y-m-t"); //Get last day
$dateMinus12 = $date->modify("-12 months"); // Last day 12 months ago

【讨论】:

  • 如果我添加一个 echo $dateMinus12;到writephponline.com 的语法和测试结束,没有什么是回声
  • 试试echo $dateMinus12->format('Y-m-d');
  • 为什么会返回 2 y$date = new DateTime(); //今天 $dateMinus12 = $date->modify("-12 个月"); // 12 个月前的最后一天 $dateMinus12end = $date->modify("-12 个月"); echo $dateMinus12->format('Y-m-01'); echo $dateMinus12end->format('Y-m-t');ears and present 2015-08-01 and 2015--8-31????
  • 这是因为您要在 $dateMinus12end = $date->modify("-12 months"); 中再删除 12 个月。您只想重新格式化它以获得最后一天:$dateMinus12end = $date->format("Y-m-t");
  • 仅供参考,像这样加减月份会产生意想不到的结果。 See example #2 in the documentation
猜你喜欢
  • 1970-01-01
  • 2015-04-29
  • 1970-01-01
  • 1970-01-01
  • 2023-03-03
  • 2012-12-15
  • 1970-01-01
  • 1970-01-01
  • 2018-09-12
相关资源
最近更新 更多