php var到年和月

时间:2010-10-14 06:31:52

标签: php date

$date ='20101015';

如何转换为$year = 2010$month = 10$day =15

感谢

3 个答案:

答案 0 :(得分:4)

您可以将PHP子字符串函数substr用作:

$year  = substr($date,0,4);  # extract 4 char starting at position 0.
$month = substr($date,4,2);  # extract 2 char starting at position 4.
$day   = substr($date,6);    # extract all char starting at position 6 till end.

如果您的原始字符串作为前导或尾随空格,则会失败,因此更好地将substr修剪输入作为。因此,在致电substr之前,您可以这样做:

$date = trim($date);

答案 1 :(得分:2)

您可以使用

一次性完成所有操作
  • sscanf - 根据格式
  • 解析字符串中的输入

示例:

list($y, $m, $d) = sscanf('20101015', '%4d%2d%2d');

sscanf('20101015', '%4d%2d%2d', $y, $m, $d);

答案 2 :(得分:1)

您可以使用子字符串函数

http://www.w3schools.com/php/func_string_substr.asp

$year=substr($date,0,4);
$month=substr($date,4,2);
$day=substr($date,6,2);