MySQL時間関数from_unixtime()date_format()unix_timestamp()now()使用説明


MySQL時間関数from_unixtime()date_format()unix_timestamp()now()使用説明
now()現在時刻
mysql> select now();
+---------------------+
| now()               |
+---------------------+
| 2018-09-10 19:20:19 |
+---------------------+

unix_timestamp()現在のタイムスタンプ
mysql> select unix_timestamp();
+------------------+
| unix_timestamp() |
+------------------+
|       1536578429 |
+------------------+

unix_timestamp(now())現在の時間をタイムスタンプに変換
mysql> select unix_timestamp(now());
+-----------------------+
| unix_timestamp(now()) |
+-----------------------+
|            1536578445 |
+-----------------------+

unix_timestamp(‘2018-08-08’)指定時間をタイムスタンプに変換
mysql> select unix_timestamp('2018-08-08');
+------------------------------+
| unix_timestamp('2018-08-08') |
+------------------------------+
|                   1533657600 |
+------------------------------+

from_unixtime(1533657600)タイムスタンプをタイムデフォルトフォーマット'%Y-%m-%d%H:%i:%s'に変換
mysql> select from_unixtime(1533657600);
+---------------------------+
| from_unixtime(1533657600) |
+---------------------------+
| 2018-08-08 00:00:00       |
+---------------------------+

from_unixtime(1533657600,'%Y-%m-%d')タイムスタンプを時間に変換してフォーマット
mysql> select from_unixtime(1533657600, '%Y-%m-%d');
+---------------------------------------+
| from_unixtime(1533657600, '%Y-%m-%d') |
+---------------------------------------+
| 2018-08-08                            |
+---------------------------------------+

クエリーのタイムスタンプフィールドをタイムフォーマット表示に変換
mysql> select from_unixtime(ctime, '%Y-%m-%d') from logs limit 1;
+----------------------------------+
| from_unixtime(ctime, '%Y-%m-%d') |
+----------------------------------+
| 2018-09-18                       |
+----------------------------------+

whereタイムスタンプフィールド
mysql> select count(*) from logs where from_unixtime(ctime, '%Y%m%d')=20180808 limit 1;
+----------+
| count(*) |
+----------+
|    12345 |
+----------+

date_format()時間をフォーマット表示する
mysql> select date_format(now(), '%Y/%m/%d');
+--------------------------------+
| date_format(now(), '%Y/%m/%d') |
+--------------------------------+
| 2018/08/08                     |
+--------------------------------+

where時間フィールド
mysql> select count(*) from logs where date_format(cdate, '%Y%m%d')=20180910 limit 1;
+----------+
| count(*) |
+----------+
|      123 |
+----------+