更新时间:2023-11-23 21:15:22
使用 t
你的日期('Ym-t')
打电话给你:
t
- 给定月份的天数
如果您尝试 Ymd
你会发现这是两个不同的日期:
?php
var_dump(date('Ym-d'));
var_dump(date('Y-m-d',strtotime(' - 1 month')));
string(10)
-31
string(10)2016-03-02
要解决此问题,您可以使用上个月的最后一天的 strtotime
格式 code>
<?php
var_dump(date('Ym-d '));
var_dump(date('Y-m-d',strtotime('last last of last month')));
导致:
string(10)
2016-03-31
string(10)-29
I've just noticed that PHP date function acts weird, can someone explain me what i'm doing wrong?
Following code displays same results
<?php
echo date('Y-m-t');
// Outputs last day of this month: 2016-03-31
echo date('Y-m-t', strtotime("-1 month"));
// For some reason outputs the same: 2016-03-31
echo date('Y-m-t', strtotime("+1 month"));
// Outputs 2016-05-31
It might be just me being stupid, but could someone explain me why this happens?
When using t
in your date('Y-m-t')
call you're referring to:
t
- Number of days in the given month
If you tried Y-m-d
you'd figure out that it's 2 different dates:
<?php
var_dump( date('Y-m-d') );
var_dump( date('Y-m-d', strtotime('-1 month') ) );
string(10) "
2016-03-31
"
string(10) "2016-03-02
"
To fix this issue you can use the strtotime
format last day of last month
:
<?php
var_dump( date('Y-m-d') );
var_dump( date('Y-m-d', strtotime('last day of last month') ) );
which results in:
string(10) "
2016-03-31
"
string(10) "2016-02-29
"