PHP-MYSQL: Converting Unix Timestamp to DateTime and vice versa

邮差的信 提交于 2019-11-30 10:56:06

Your date format is wrong... i is for minute, not m (months).

return date("Y-m-d H:i:s", $unixTimestamp);

A few side notes:

  • There's no need to re-assign, i.e. $unixTimestamp = $unixTimestamp;
  • Since you're using PHP > 5.3. you may be interested in the new DateTime object.

The problem lies in the function you wrote:

return date("Y-m-d H:m:s", $unixTimestamp);

You specify month(m) in both the date and time portions. You should replace the second m with i, the correct flag for hours when using date() in PHP.

return date("Y-m-d H:i:s", $unixTimestamp);

Depending on your needs you might find the PHP function strtotime() useful enough.

Why not simply use the FROM_UNIXTIME function in mysql ?

user3723383
function format_date($str) {
    $month = array(" ", "Jan", "Feb", "Mar", "Apr", "May", "June", "July", "Aug", "Sep", "Oct", "Nov", "Dec");
    $y = explode(' ', $str);
    $x = explode('-', $y[0]);
    $date = "";    
    $m = (int)$x[1];
    $m = $month[$m];
    $st = array(1, 21, 31);
    $nd = array(2, 22);
    $rd = array(3, 23);
    if(in_array( $x[2], $st)) {
            $date = $x[2].'st';
    }
    else if(in_array( $x[2], $nd)) {
            $date .= $x[2].'nd';
    }
    else if(in_array( $x[2], $rd)) {
            $date .= $x[2].'rd';
    }
    else {
            $date .= $x[2].'th';
    }
    $date .= ' ' . $m . ', ' . $x[0];

    return $date;
}

nothing of both. you should save the timestamp as an INT or BIGINT because if you use the TIMESTAMP format of mysql you will never ever get it back to an int. You can only get something like this 1970-01-01 01:00:00.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!