3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

MySQLのタイムゾーン変換で少しはまった件

Last updated at Posted at 2018-01-28

EPOCH時間をタイムスタンプに変換

from_unixtime()関数で得られる。

mysql> select from_unixtime(1517136662);
+---------------------------+
| from_unixtime(1517136662) |
+---------------------------+
| 2018-01-28 19:51:02       |
+---------------------------+
1 row in set (0.02 sec)

ただし、この時返ってくるタイムスタンプのタイムゾーンはMySQLのtime_zoneの設定値に依存する。
上記の例はJSTの場合。

タイムゾーンの設定に依存せずに常にUTCで取得したかったので以下のようなSQLを書いたところnullが返ってきた。

mysql> convert_tz(from_unixtime(1517136662), @@session.time_zone, 'utc');
+-------------------------------------------------------------------+
| convert_tz(from_unixtime(1517136662), @@session.time_zone, 'utc') |
+-------------------------------------------------------------------+
| NULL                                                              |
+-------------------------------------------------------------------+
1 row in set (0.00 sec)

どうやらタイムゾーンテーブルなるものをロードしなければならないらしい。

$ mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql -u root mysql
mysql> select convert_tz(from_unixtime(1517136662), @@session.time_zone, 'utc');
+-------------------------------------------------------------------+
| convert_tz(from_unixtime(1517136662), @@session.time_zone, 'utc') |
+-------------------------------------------------------------------+
| 2018-01-28 10:51:02                                               |
+-------------------------------------------------------------------+
1 row in set (0.00 sec)
3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?