设置日期时间格式


Formatting datetime

>我正在尝试以以下格式格式化来自数据库的日期时间

2012-06-11 21:39:54

但是我希望它以June 11格式显示

怎么能做到这一点?

谢谢

echo date('M d', strtotime('2012-06-11 21:39:54'));

输出

您也可以使用 DateTime 对象。

$date = new DateTime($yourString);
$date->format($yourFOrmat);

我认为这将是最好的方法,因为日期时间确实比时间戳和日期/strtotime 函数更强大。从我上面给出的代码中,您可以添加修改日期、迭代时间、比较 2 个日期等功能,而无需str_to_time等功能......

$date->modify('+1 day');//the day after for example
foreach(new DatePeriod($date,new DateInterval('PT1M'),10){
    $date->format($yourFormat);//iterate each minute
}  

等等

PHP 手册提供了关于使用日期/时间函数的优秀文档。基本上你需要两个函数的组合:strtotime() 和 date()。

strtotime() 会将您的日期转换为 Unix 时间戳,该时间戳可以作为第二个参数提供给date()

您需要的日期格式为:M d

替代方案:此外,您还可以尝试不需要转换为UNIX时间戳的MYSQL对应物。此处记录了它。假设您使用date作为日期时间字段,您将需要这样的东西,

SELECT id,..,DATE_FORMAT(`date`, '%M %d') as f_date FROM table

要使用 php 格式化日期,您需要传递日期
的时间戳并将说明符格式化为参数到日期函数中。例如回声日期('M d',strtotime('2012-06-11 21:39:54'));