如何使用preg_split格式化日期

时间:2011-03-30 16:08:51

标签: php regex timestamp

2011-03-30 17:47:31 所以这是我的mysql数据库中的日期;

我该怎么办呢?

我希望它看起来像30/03/2011 | 17点47分31秒

4 个答案:

答案 0 :(得分:2)

使用SQL查询中的DATE_FORMAT函数,以所需格式提取日期。

答案 1 :(得分:2)

date('d/m/Y | G:i:s', strtotime($theOriginalTime))

那应该做你需要的。

答案 2 :(得分:1)

我不确定你为什么要使用preg_split,只需这样做:

date("d/m/Y | G:i:s", strtotime($timestamp));

或者使用UNIX_TIMESTAMP()从MySQL获取unix时间戳,然后执行:

date("d/m/Y | G:i:s", $unix_timestamp);

答案 3 :(得分:0)

使用正则表达式很容易解决这个问题。这是一个经过测试的PHP函数,它重新格式化给定文本字符串中的任何和所有此类日期:

function convert_dates($text) {
    // Convert 2011-03-30 17:47:31 to 30/03/2011 | 17:47:31
    $re = '/# Match components of a YYYY-MM-DD HH:MM:SS date.
        \b                     # Begin on word boundary
        (\d{4})-               # $1: Year.
        (\d{2})-               # $2: Month.
        (\d{2})[ ]             # $3: Day.
        (\d{2}):               # $4: Hour.
        (\d{2}):               # $5: Minute.
        (\d{2})                # $6: Second.
        \b                     # End on word boundary.
        /Sx';
    $replace = '$3/$2/$1 | $4:$5:$6';
    return preg_replace($re, $replace, $text);
}