如何在PHP中将Y-m-d H:i:s转换为Y-m-d?
我有一个例如:
我有一个例如:
$date = "2011-08-10 20:40:12";
我想将其转换为
$output = "2011-08-10";
提前感谢您。
快速/简单:
$output = substr('2011-08-10 20:40:12', 0, 10);
稍微更加健壮:
$output = date('Y-m-d', strtotime('2011-08-10 20:40:12'));
相当可靠:
$output = DateTime::createFromFormat('Y-m-d h:i:s', '2011-08-10-20:40:12')->format('Y-m-d');
使用 strtotime()
可以轻松完成,而且还能更改为您需要的任何其他日期格式。
$old_date = "2011-08-10 20:40:12";
$new_date = date("Y-m-d", strtotime($old_date));
echo $new_date;
// Prints 2011-08-10
$output = substr($date, 0, 10);
$date = date_format($date, 'Y-m-d');
另一种解决方案是使用子字符串,虽然不太好:
$newDate = substr($date, 0, 10)
$old_date = "2011-08-10 20:40:12";
$new_date = date("Y-m-d", strtotime($old_date));
echo $new_date;
// Prints 2011-08-10
这应该非常有用。
$date = date("Y-m-d", strtotime($date));
只需使用日期格式来表示日期,然后将您的字符串转换为时间戳即可。
我更喜欢使用strftime
而不是date
,因为它的格式输入与C和其他语言中的格式匹配。
$output = strftime( '%Y-%m-%d', strtotime( $date) );
通过对使用explode方法进行微调,您可以将其转换为一行代码:
list($date) = explode(' ', $date);
list函数在处理日期方面非常方便。
另一个使用list的例子:
list($year, $month, $day) = explode(' ', $date);
此外,在字符串中最好使用'而不是",除非您的字符串包含变量。
例如:
我已经厌倦了看到甚至PHP文档在应该使用'string'的示例中使用"string" :o)
尝试:
$date = explode(" ",$date);
$output = $date[0];