PHP: 一个简单的字符串到日期对象转换失败
PHP: a simple string to date object conversion fails
我想将获取的字符串转换为日期对象,这样我就可以 add/substract 天 to/from 了。我尝试了在网上阅读的几种方法,但都失败了,我完全迷路了(这应该很容易!)。这是一个例子:
echo '11: '.substr($content, 0, 10).'<br/>';
$theDay = new datetime(substr($content, 0, 10));
echo '2: '.$theDay->format('yyyy-mm-dd').'<br/>';
$theDay->modify('+1 day');
echo '21: '.$theDay->format('yyyy-mm-dd').'<br/>';
我得到的输出是:
11: 2016-02-10
2: 16161616-0202-1010
21: 16161616-0202-1111
第一行显示日期结构正确,第二行看起来很奇怪!在添加 1 天之后,它看起来好像确实添加了 1 天(11 而不是 10),但它看起来又很奇怪。我错过了什么?
你的格式字符串搞砸了:
echo '11: '.substr($content, 0, 10).'<br/>';
$exDay = new datetime(substr($content, 0, 10));
echo '2: '.$exDay->format('Y-m-d').'<br/>';
$exDay->modify('+1 day');
echo '21: '.$exDay->format('Y-m-d').'<br/>';
输出:
11: 2016-02-10
2: 2016-02-10
21: 2016-02-11
有关格式字符的完整列表,请参阅 the manual。与此问题相关的是:
Y A full numeric representation of a year, 4 digits
y A two digit representation of a year
m Numeric representation of a month, with leading zeros
d Day of the month, 2 digits with leading zeros
即,您不写 yyyy
表示 4 位数的年份,而是写 Y
(m
和 d
也是如此)。
我想将获取的字符串转换为日期对象,这样我就可以 add/substract 天 to/from 了。我尝试了在网上阅读的几种方法,但都失败了,我完全迷路了(这应该很容易!)。这是一个例子:
echo '11: '.substr($content, 0, 10).'<br/>';
$theDay = new datetime(substr($content, 0, 10));
echo '2: '.$theDay->format('yyyy-mm-dd').'<br/>';
$theDay->modify('+1 day');
echo '21: '.$theDay->format('yyyy-mm-dd').'<br/>';
我得到的输出是:
11: 2016-02-10
2: 16161616-0202-1010
21: 16161616-0202-1111
第一行显示日期结构正确,第二行看起来很奇怪!在添加 1 天之后,它看起来好像确实添加了 1 天(11 而不是 10),但它看起来又很奇怪。我错过了什么?
你的格式字符串搞砸了:
echo '11: '.substr($content, 0, 10).'<br/>';
$exDay = new datetime(substr($content, 0, 10));
echo '2: '.$exDay->format('Y-m-d').'<br/>';
$exDay->modify('+1 day');
echo '21: '.$exDay->format('Y-m-d').'<br/>';
输出:
11: 2016-02-10
2: 2016-02-10
21: 2016-02-11
有关格式字符的完整列表,请参阅 the manual。与此问题相关的是:
Y A full numeric representation of a year, 4 digits
y A two digit representation of a year
m Numeric representation of a month, with leading zeros
d Day of the month, 2 digits with leading zeros
即,您不写 yyyy
表示 4 位数的年份,而是写 Y
(m
和 d
也是如此)。