首页 > 数据库 > MySQL > 正文

MySQL timestamp的类型与时区实例详解

2024-07-24 12:53:16
字体:
来源:转载
供稿:网友

 MySQL timestamp的类型与时区

MySQL的timestamp类型时间范围between '1970-01-01 00:00:01' and '2038-01-19 03:14:07',超出这个范围则值记录为'0000-00-00 00:00:00',该类型的一个重要特点就是保存的时间与时区密切相关,上述所说的时间范围是UTC(Universal Time Coordinated)标准,指的是经度0度上的标准时间,我国日常生活中时区以首都北京所处的东半球第8区为基准,统一使用东8区时间(俗称北京时间),比UTC要早8个小时,服务器的时区设置也遵照此标准,因此对应过来timestamp的时间范围则应校准为'1970-01-01 08:00:01' and '2038-01-19 11:14:07',也就是说东八区的1970-1-1 08:00:01等同于UTC 1970-1-1 00:00:01。

需要特点注意,timestamp类型的时间不仅仅与写入记录时的时区有关,显示时也与时区有关,例如:

mysql> desc j1_dt;+-------+-----------+------+-----+-------------------+-------+| Field | Type | Null | Key | Default | Extra |+-------+-----------+------+-----+-------------------+-------+| dt | timestamp | NO | | CURRENT_TIMESTAMP | | +-------+-----------+------+-----+-------------------+-------+1 row in set (0.00 sec)mysql> insert into j1_dt values ('1970-01-01 08:00:01');Query OK, 1 row affected (0.00 sec)mysql> select * from j1_dt;+---------------------+| dt |+---------------------+| 1970-01-01 08:00:01 | +---------------------+1 row in set (0.00 sec)mysql> set time_zone='+0:00';Query OK, 0 rows affected (0.00 sec)mysql> select * from j1_dt;+---------------------+| dt |+---------------------+| 1970-01-01 00:00:01 | +---------------------+1 row in set (0.00 sec)mysql> set time_zone='+1:00';Query OK, 0 rows affected (0.00 sec)mysql> select * from j1_dt;+---------------------+| dt |+---------------------+| 1970-01-01 01:00:01 | +---------------------+1 row in set (0.00 sec)

如上述所示,根据时区的不同,显示的日期也是不一样的,这正是timestamp类型在MySQL日期类型中独有的时区特点。

如果向timestamp类型列插入的值超出了指定范围,则实际实际保存的值为'0000-00-00 00:00:00',并触发一个警告信息:

mysql> set time_zone='+8:00';Query OK, 0 rows affected (0.00 sec)mysql> select * from j1_dt;+---------------------+| dt |+---------------------+| 1970-01-01 08:00:01 | +---------------------+1 row in set (0.00 sec)mysql> insert into j1_dt values ('1970-01-01 00:00:01');Query OK, 1 row affected, 1 warning (0.00 sec)mysql> show warnings;+---------+------+------------------------------------------------------+| Level | Code | Message |+---------+------+------------------------------------------------------+| Warning | 1264 | Out of range value adjusted for column 'dt' at row 1 | +---------+------+------------------------------------------------------+1 row in set (0.00 sec)mysql> select * from j1_dt;+---------------------+| dt |+---------------------+| 1970-01-01 08:00:01 | | 0000-00-00 00:00:00 | +---------------------+2 rows in set (0.00 sec)
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表