PHP-如何从时间字符串获取年,月,日 [英] PHP - How to get year, month, day from time string

查看:911
本文介绍了PHP-如何从时间字符串获取年,月,日的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下时间字符串:

$str = '2000-11-29';

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

如何用PHP获取年/月/日?

How to get the year/month/day in PHP?

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

我不知道为什么我要1969年.

I don't know why I get 1969 for year.

谢谢

推荐答案

您可以使用 strtotime 解析时间字符串,并将生成的时间戳传递给 getdate (或使用

You can use strtotime to parse a time string, and pass the resulting timestamp to getdate (or use date to format your time).

$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!';
}

请注意,如果时间字符串无效或无法解析,则strtotime将返回false.当您要解析的时间戳无效时,您将遇到以前遇到的1969-12-31日期.

Note that strtotime will return false if the time string is invalid or can't be parsed. When the timestamp you're trying to parse is invalid, you end up with the 1969-12-31 date you encountered before.

这篇关于PHP-如何从时间字符串获取年,月,日的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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