如何在PHP中转换日期格式?

时间:2014-01-27 10:54:50

标签: php mysql datetime

我从数据库中获取数据,它以2014-01-06 06:13:06的格式提供日期。我想将此日期转换为Jan 6th 2014格式。

这是我的代码:

<?php 
$query="SELECT Min(transaction_date) as start,Max(transaction_date) as end from transactions";
$result1= mysql_query($query) or die(mysql_error());
$ors1=mysql_fetch_array($result1);
$date= $ors1['start'];
echo date_format($date, 'g:ia \o\n l jS F Y');
?>

5 个答案:

答案 0 :(得分:1)

试试这个

 <?php 
    $query="SELECT Min(transaction_date) as start,Max(transaction_date) as end from transactions";
    $result1= mysql_query($query) or die(mysql_error());
    $ors1=mysql_fetch_array($result1);
    $date= $ors1['start'];
    echo date('dS M Y' ,strtotime($date));
 ?>

参考网址:PHP Documentation

答案 1 :(得分:0)

使用strtotime从时间的字符串表示中获取时间戳。 然后使用date将时间戳格式化为您想要的任何格式。

e.g。

$formatted_date = date('g:ia \o\n l jS F Y', strtotime('2014-01-06 06:13:06 '));

答案 2 :(得分:0)

你也可以尝试这样:

<?php
echo 'Current time: ' . date('Y-m-d H:i:s') . "\n";

$format = 'Y-m-d';
$date = DateTime::createFromFormat($format, '2009-02-15');
echo "Format: $format; " . $date->format('Y-m-d H:i:s') . "\n";

$format = 'Y-m-d H:i:s';
$date = DateTime::createFromFormat($format, '2009-02-15 15:16:17');
echo "Format: $format; " . $date->format('Y-m-d H:i:s') . "\n";

$format = 'Y-m-!d H:i:s';
$date = DateTime::createFromFormat($format, '2009-02-15 15:16:17');
echo "Format: $format; " . $date->format('Y-m-d H:i:s') . "\n";

$format = '!d';
$date = DateTime::createFromFormat($format, '15');
echo "Format: $format; " . $date->format('Y-m-d H:i:s') . "\n";
?>

以上示例将输出类似于:

的内容
Current time: 2010-04-23 10:29:35
Format: Y-m-d; 2009-02-15 10:29:35
Format: Y-m-d H:i:s; 2009-02-15 15:16:17
Format: Y-m-!d H:i:s; 1970-01-15 15:16:17
Format: !d; 1970-01-15 00:00:00

了解更多信息:http://in1.php.net/manual/en/datetime.createfromformat.php

答案 3 :(得分:0)

您可以在MySQL

中自行尝试
SELECT 
    DATE_FORMAT(start, '%M %D %Y') as start_formatted,
    DATE_FORMAT(end, '%M %D %Y') as end_formatted
FROM
    (SELECT 
        Min(transaction_date) as start, Max(transaction_date) as end
    from
        transactions) t;

示例

mysql> SELECT DATE_FORMAT(NOW(),'%M %D %Y');
+-------------------------------+
| DATE_FORMAT(NOW(),'%M %D %Y') |
+-------------------------------+
| January 27th 2014             |
+-------------------------------+
1 row in set (0.00 sec)

答案 4 :(得分:0)

试试这个

$date= $ors1['start'];
$objdate=new DateTime($date);
echo date_format($objdate, 'g:ia \o\n l jS F Y');