PHP - 如何从时间字符串获取年,月,日

php
2022-08-30 16:23:30

给定以下时间字符串:

$str = '2000-11-29';

$php_date = getdate( $str );
echo '<pre>';
print_r ($php_date);
echo '</pre>';

如何获得PHP的年/月/日?

[seconds] => 20
[minutes] => 33
[hours] => 18
[mday] => 31
[wday] => 3
[mon] => 12
[year] => 1969
[yday] => 364
[weekday] => Wednesday
[month] => December
[0] => 2000

我不知道为什么我会得到1969年。

谢谢


答案 1

可以使用 strtotime 分析时间字符串,并将生成的时间戳传递给 getdate(或使用 date 设置时间的格式)。

$str = '2000-11-29';

if (($timestamp = strtotime($str)) !== false)
{
  $php_date = getdate($timestamp);
  // or if you want to output a date in year/month/day format:
  $date = date("Y/m/d", $timestamp); // see the date manual page for format options      
}
else
{
  echo 'invalid timestamp!';
}

请注意,如果时间字符串无效或无法解析,将返回。当您尝试解析的时间戳无效时,您最终会得到您之前遇到的 1969-12-31 日期。strtotimefalse


答案 2

PHP - 如何从时间字符串获取年,月,日

$dateValue = strtotime($q);                     

$yr = date("Y", $dateValue) ." "; 
$mon = date("m", $dateValue)." "; 
$date = date("d", $dateValue); 

推荐