💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
## 语法 ~~~ strtotime(time,now); ~~~ | 参数 | 描述 | | --- | --- | | *time* | 必需。规定日期/时间字符串。 | | *now* | 可选。规定用来计算返回值的时间戳。如果省略该参数,则使用当前时间。 | 最近做数据可视化 用的图表 echarts.js 然后传参横坐标日期时用到了strtotime这个函数,结果发现有坑,昨天是2019-05-30都是正常的,发版后今天31号就全错了 原代码 ``` // 以指定格式$format,显示最近$monthLong个月的数据,用来作为图标横坐标 function createMonthLine($monthLong, $format= "ym"){ $monthLine = []; for ($i=1; $i<= $monthLong; $i++){ $monthLine[] = date($format, strtotime("-".($monthLong-$i)." month")); } return $monthLine; } ``` 新代码 ``` function createMonthLine($monthLong, $format= "ym"){ $monthLine = []; for ($i=1; $i<= $monthLong; $i++){ $monthLine[] = date($format, strtotime("first day of -".($monthLong-$i)." month")); } return $monthLine; } ``` 其中的原理,见鸟哥博客分析: http://www.laruence.com/2018/07/31/3207.html 大概原因是 如下规则 ## 以当前传值日期 按照要求处理年月日 如果年月日被处理后超过了合理值,会自动进一位;当月日满进月位, 当年月满进年位 试下几个代码就知道问题了 ``` var_dump(date("Y-m-d", strtotime("2019-02-31"))); # 2019-03-03 # 2019年的2月只有28天 日满进月 日取余; 变为2019-03-03 符合 var_dump(date("Y-m-d", strtotime("2019-12-32"))); # 1970-01-01 # 不符合期望 以为会是 12月没有32 进1月 然后月满进年 最后为 2020-01-01 var_dump(date("Y-m-d", strtotime("2019-13-01"))); # 1970-01-01 # 不符合期望 以为会是 1年没有12个月 进1年 最后为 2020-01-01 var_dump(date("Y-m-d", strtotime("-1 month", strtotime("2019-08-31")))); # 2019-07-31 正常日期 var_dump(date("Y-m-d", strtotime("+1 month", strtotime("2019-08-31")))); # 2019-10-01 9月没有31号,日满进月 var_dump(date("Y-m-d", strtotime("-1 month", strtotime("2019-03-27")))); # 2019-02-27 也并不是评论里所说减去上个月的天数 var_dump(date("Y-m-d", strtotime("+1 month", strtotime("2019-12-31")))); # 2020-01-31 月满进年 var_dump(date("Y-m-d", strtotime("-1 month", strtotime("2020-01-31")))); # 2019-12-31 月减退年 var_dump(date("Y-m-d", strtotime("2020-01-31 -1 month"))); # 2019-12-31 月减退年 ``` 结论如下: 1.进位规则在显示指定被处理的日期时, 日进位退位正常,月退位正常,进位异常,会导致年变成1970 2.进位规则在默认指定被处理日期为当前时, 日月年进位退位均正常 ## 回看这里时,突然发现实际的需求其实是获得上月或者下月的同期。比如 ### 昨天 ``` date('Y-m-d', strtotime('yesterday')); date('Y-m-d', strtotime('last day')); ``` ### 明天 ``` date('Y-m-d', strtotime('tomorrow')); date('Y-m-d', strtotime('next day')); ``` ### 月初 ``` date('Y-m-01'); date('Y-m-d', strtotime('first day of this month')); ``` ### 月末 ``` date('Y-m-01'); date('Y-m-d', strtotime('last day of this month')); ``` ### 形容性日期 有 of 默认参照都是今天今月今天 \*年\*月的X天,其中*可以为 last this next 分别代表{上|本|下}{月|年},X可以为first last 表示{第一|最后}天 ``` date('Y-m-d', strtotime('X day of * month * year')); ``` ### 非形容性日期 无 of 默认参照都是今天今月今天 \*年\*月的\*天,其中*可以为 last this next 分别代表{上|本|下}{月|年} ``` date('Y-m-d', strtotime('X day * month * year')); ```