PHP-MYSQL:将 Unix 时间戳转换为 DateTime,反之亦然

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14883617/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 08:07:29  来源:igfitidea点击:

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

phpmysqldatetimeunix-timestamp

提问by sockeqwe

im using php 5.4.6 and MySQL 5.5.29 and I get trouble by converting a UNIX TIMESTAMP to MYSQL DATETIME and vice versa. Mysql and php wun on the same local machine.

我正在使用 php 5.4.6 和 MySQL 5.5.29,我在将 UNIX TIMESTAMP 转换为 MYSQL DATETIME 时遇到了麻烦,反之亦然。Mysql 和 php wun 在同一台本地机器上。

I have a simple mysql table

我有一个简单的 mysql 表

CREATE TABLE Entry(
id SERIAL PRIMARY KEY,
created DATETIME NOT NULL);

To insert data I use php PDO and mysql NOW(). This works fine, the correct datetime is stored in the database.

要插入数据,我使用 php PDO 和 mysql NOW()。这工作正常,正确的日期时间存储在数据库中。

My plan is to work with unix timestamps on client side (php & mysql on server side).

我的计划是在客户端使用 unix 时间戳(服务器端使用 php 和 mysql)。

So I would like to deliver unix timestamps to my client. Therefore I use MySql UNIX_TIMESTAMP() function to convert it directly in the query.

所以我想向我的客户提供 unix 时间戳。因此我使用 MySql UNIX_TIMESTAMP() 函数直接在查询中转换它。

So a sample query looks like this:

因此,示例查询如下所示:

SELECT created, UNIX_TIMESTAMP(created) AS TS FROM Entry

The result: created = 2013-02-14 20:47:35 TS = 1360871255

结果:created = 2013-02-14 20:47:35 TS = 1360871255

So now I want to do the other way, I pass the a UNIX Timestamp, and want to compare it with Entries in my Database. Unfortunetly Im not able to write a PHP script that works. I don't know why, but when I m passing the same timestamp (1360871255) to PHP I do not get 2013-02-14 20:47:35 with this method:

所以现在我想做另一种方式,我传递一个 UNIX 时间戳,并想将它与我的数据库中的条目进行比较。不幸的是,我无法编写有效的 PHP 脚本。我不知道为什么,但是当我将相同的时间戳 (1360871255) 传递给 PHP 时,我没有使用这种方法得到 2013-02-14 20:47:35:

public static function toDateTime($unixTimestamp){
    return date("Y-m-d H:m:s", $unixTimestamp);
}

When I call toDateTime(1360871255) will return 2013-02-14 20:02:35 which is not the original DateTime.

当我调用 toDateTime(1360871255) 将返回 2013-02-14 20:02:35 这不是原始的 DateTime。

I know, I dont need to format 1360871255 to a Y-m-d H:m:s to use it in MYSQL, but 1360871255 seems not to be the time that I expected (and MYSQL UNIX_TIMESTAMP has returned).

我知道,我不需要将 1360871255 格式化为 Ymd H:m:s 即可在 MYSQL 中使用它,但是 1360871255 似乎不是我预期的时间(并且 MYSQL UNIX_TIMESTAMP 已经返回)。

What I want to do is a simple query that shows me Entries that are older than a certain timestamp, something simple like this:

我想要做的是一个简单的查询,它向我显示比某个时间戳更早的条目,就像这样简单:

SELECT * FROM Entry WHERE created < 1360871255

but as I mentioned before, the query result is not the expected, because 1360871255 seems not to be the correct time.

但正如我之前提到的,查询结果不是预期的,因为 1360871255 似乎不是正确的时间。

I do not specify any special timezone for the mysql connection in php.

我没有为 php 中的 mysql 连接指定任何特殊的时区。

Any suggestions?

有什么建议?

回答by Jason McCreary

Your date formatis wrong... iis for minute, not m(months).

您的日期格式错误...i是分钟,而不是m(月)。

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 DateTimeobject.
  • 无需重新分配,即 $unixTimestamp = $unixTimestamp;
  • 由于您使用的是 PHP > 5.3。您可能对新的DateTime对象感兴趣。

回答by BadAlgorithm

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 mwith i, the correct flag for hours when using date() in PHP.

您可以在日期和时间部分中指定月份 (m)。此时应更换第二使用PHP日期()时,正确的标志小时。

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

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

根据您的需要,您可能会发现 PHP 函数 strtotime() 足够有用。

回答by Ellert van Koperen

Why not simply use the FROM_UNIXTIME function in mysql ?

为什么不简单地在 mysql 中使用 FROM_UNIXTIME 函数?

回答by 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;
}

回答by user3723383

nothing of both. you should save the timestamp as an INTor BIGINTbecause if you use the TIMESTAMPformat 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.

两者都没有。你应该时间戳保存为一个INTBIGINT因为如果你使用TIMESTAMP的MySQL的格式,你永远不会拿回来的int。你只能得到这样的东西1970-01-01 01:00:00