错误的月份(2月)-DateTime :: createFromFormat [英] Wrong month (February) - DateTime::createFromFormat

查看:166
本文介绍了错误的月份(2月)-DateTime :: createFromFormat的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

字符串的日期转换返回第二个月(二月)的错误值:

The date conversion from string returns wrong values for the 2nd month (February):

$dtformat = 'Y-m-01';
$curDate = DateTime::createFromFormat('Y-m', '1996-02');
print_r($curDate);
$dt     = $curDate->format($dtformat);
echo $dt."\n";

它返回"1996-03-01"而不是"1996-02-01".这是$currDate数组:

Instead of "1996-02-01", it returns "1996-03-01". This is the $currDate array:

DateTime Object ( 
    [date] => 1996-03-02 01:19:01 
    [timezone_type] => 3 
    [timezone] => America/New_York 
)

所有其他月份工作正常.我在这里想念什么?

All other months work fine. What am I missing here?

谢谢!

推荐答案

根据此帖子.

原因:当我们不向createFromFormat提供日期时,默认为今天.因此,在这种情况下将是1996-02-31,它不存在&因此将需要下个月.

Cause: When we don't provide date to createFromFormat it will take as today's date by default. So in this case it will be 1996-02-31 which does not exist & thus it will take a next month.

解决方案::需要提供一天的时间来避免这种情况.

Solution: Need to provide day to avoid such scenario.

$date = "2011-02";
echo $date."\n";
$d = DateTime::createFromFormat("Y-m-d",$date."-01");
echo $d->format("Y-m");

这篇关于错误的月份(2月)-DateTime :: createFromFormat的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆