如何在PHP中获取日期字段?

时间:2013-08-12 08:59:19

标签: php

如何在php中获取日期的值? 例如,我有这样的日期:

$date = "2013-01-29";

我想要的是将年份和月份分配给变量。

示例:

$year = "2013";

$month = "01";

$day = "29";

我该怎么做?

5 个答案:

答案 0 :(得分:4)

比@TobSpr更多的OOP方式将使用DateTime

$date = "2013-01-29";
$dt = new DateTime($date);

echo $dt->format('Y');

这样做的好处是我们可以完全控制日期,我们甚至可以指定一个特定的时区,处理格式错误的输入日期字符串(DateTime __construct将在不可解析的输入上抛出异常)

$date = "2013-01-29 invalid";
try {
    $dt = new DateTime($date);
    echo $dt->format('Y');
} catch (Exception $e) {
    printf('Failed to decode input date "%s", PHP said: %s', $date, $e->getMessage());
}

有关可以发送到DateTime::format的内容的信息,请参阅date

答案 1 :(得分:1)

$date = new DateTime('2013-01-29');
echo $date->format("Y");
echo $date->format("m");
echo $date->format("d");

答案 2 :(得分:0)

使用strtotime(),将各种格式的字符串转换为日期。它可以检测各种日期格式:

$date_unix = strtotime($date);
$year = date("Y", $date_unix);
$month = date("m", $date_unix);
$day = date("d", $date_unix);

另请参阅date()以获取所有修饰符的列表。

答案 3 :(得分:-2)

简单

$newdate=explode("-",$date);
$day=$newdate[2];
$month=$newdate[1];
$year=$newdate[0];

答案 4 :(得分:-2)

在php中你可以通过以下方式完成它               $ date =“2013-01-29”;               $ TEM =爆炸( “ - ”,$日期);               $ =每年$ TEM [0];               每月$ = $温度[1];               $天= $温度[2];