简体   繁体   English

获取月份的最后日期错误

[英]get last date in month error

I have the following code which gets the date parsed, the subtracts 1 month. 我有以下代码,该代码获取解析的日期,减去1个月。 This works perfectly. 这很完美。

$date = '22-05-2016';
print(date("Y-m-d 23:59:59", strtotime($date.' -1 months')));
// outputs 2016-04-22 23:59:59

There are times where I need to force the date to month end. 有时我需要将日期强制为月底。 For this I use Ymt instead of Ymd Which works perfectly. 为此,我使用Ymt而不是Ymd它可以很好地工作。

$date = '22-05-2016';
print(date("Y-m-t 23:59:59", strtotime($date.' -1 months')));
// outputs 2016-04-30 23:59:59


The problem comes when the date that is parsed is actually the last day of that month. 问题是当解析的日期实际上是该月的最后一天时。 It then flips to end of the next month. 然后翻转到下个月结束。

 $date = '31-05-2016'; print(date("Ymt 23:59:59", strtotime($date.' -1 months'))); 

Actual Output 2016-05-31 23:59:59 (hasn't removed 1 month) 实际输出2016-05-31 23:59:59 (1个月未移除)

Desired Output 2016-04-30 23:59:59 期望的输出2016-04-30 23:59:59

EDIT: Fiddle example http://ideone.com/0fqlor 编辑: 小提琴示例http://ideone.com/0fqlor

Try: 尝试:

 $date = '31-05-2016';
 print(date("Y-m-d 23:59:59", strtotime($date.'  last day of last month')));

and dig into strtotime possibilities ;) 并探讨strtotime可能性;)

Take a look here: http://php.net/manual/en/datetime.formats.relative.php 在这里看看: http : //php.net/manual/en/datetime.formats.relative.php

Last Note: -1 month only gets 30 days back in time. 最后注意事项: -1 month只能恢复30天。 Therefore it will not work allways. 因此,它将无法正常工作。 Some kind of PHP stuff, i think ;) 我认为有些PHP的东西;)

strtotime is your friend. strtotime是您的朋友。 The last day of any "given" month can be retrieved using the verbal String last day of May 2015 - so, for easy input (guess you have a date-picker not a month-picker), convert the selected date to its month expression first: 可以使用last day of May 2015last day of May 2015的语言字符串来检索任何“给定”月份的last day of May 2015 -因此,为了方便输入(猜测您使用日期选择器而不是月份选择器),请将所选日期转换为其月份表达式第一:

date_default_timezone_set('Europe/London');
$to = '31-05-2016';
$month = date("M Y", strtotime($to));
$strtotime_expression = "last day of " . $month;
echo $strtotime_expression.": <br />";
print(date("Y-m-t 23:59:59", strtotime($strtotime_expression)));

http://ideone.com/YvjVeP http://ideone.com/YvjVeP

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM