MySQL 关于时间:
一、 MySQL 获取当前时间、日期:
(1). now() 返回的时间,格式如下:2013-01-17 10:57:13
mysql> SELECT now(),sleep(5),now();
+---------------------+----------+---------------------+
| now() | sleep(5) | now() |
+---------------------+----------+---------------------+
| 2013-01-17 10:57:13 | 0 | 2013-01-17 10:57:13 |
+---------------------+----------+---------------------+
1 row in set (5.01 sec)
除了 now() 函数能获得当前的日期时间外,MySQL 中还有下面的函数:
SELECT now()
,current_timestamp()
,current_timestamp
,localtime()
,localtime
,localtimestamp
,localtimestamp();
(2). curdate(),返回时间的日期,格式如下:2013-01-17
mysql> select curdate(),sleep(5),curdate();
+------------+----------+------------+
| curdate() | sleep(5) | curdate() |
+------------+----------+------------+
| 2013-01-17 | 0 | 2013-01-17 |
+------------+----------+------------+
1 row in set (5.00 sec)
(3). curtime(), 返回时间,格式如下:12:49:26
mysql> select curtime(),sleep(5),curtime();
+-----------+----------+-----------+
| curtime() | sleep(5) | curtime() |
+-----------+----------+-----------+
| 12:49:26 | 0 | 12:49:26 |
+-----------+----------+-----------+
其返回的两个值是一样的,因为都是表示语句开始执行的时间。
(4). sysdate() 返回时间,格式和time()函数返回时间一样,。格式:2013-01-17 13:02:40
但区别在于: now() 在执行开始时值就得到了,sysdate() 在函数执行时动态得到值;
mysql> select sysdate(),sleep(5),sysdate();
+---------------------+----------+---------------------+
| sysdate() | sleep(5) | sysdate() |
+---------------------+----------+---------------------+
| 2013-01-17 13:02:40 | 0 | 2013-01-17 13:02:45 |
+---------------------+----------+---------------------+
其返回的两个值是不一样的,因为sysdate是查看的系统时间,时时的系统时间。
也正因为有这个区别,我们一般在执行语句的时候,都是用now(),因为sysdate()获取当时
实时的时间,这有可能导致主库和从库执行时返回值不一样,导致主从数据库不一致。
区别:除了本身定义所返回的区别以为,另外一个区别是:now(),curtime(),curdate()
都是返回基于语句的开始执行时间,而sysdate()返回time的值。
其它函数格式显示:
mysql> select now(),curdate(),sysdate(),curtime()\G;
*************************** 1. row ***************************
now(): 2013-01-17 13:07:53
curdate(): 2013-01-17
sysdate(): 2013-01-17 13:07:53
curtime(): 13:07:53
1 row in set (0.01 sec)
(5). 获得当前 UTC 日期时间函数:utc_date(), utc_time(), utc_timestamp()
mysql> select utc_timestamp(), utc_date(), utc_time(), now()
+---------------------+------------+------------+---------------------+
| utc_timestamp() | utc_date() | utc_time() | now() |
+---------------------+------------+------------+---------------------+
| 2008-08-08 14:47:11 | 2008-08-08 | 14:47:11 | 2008-08-08 22:47:11 |
+---------------------+------------+------------+---------------------+
因为我国位于东八时区,所以本地时间 = UTC 时间 + 8 小时。UTC 时间在业务涉及多个国家和地区的时候,非常有用。
------------------------------------------------------------------------------------------------------------------------------
二、 MySQL 时间截取
(1). 选取日期时间的各个部分:日期、时间、年、季度、月、日、小时、分钟、秒、微秒
SELECT now() #2017-11-13 17:46:50
,date(now()) AS 日期 #2017-11-13
,time(now()) AS 时间 #17:46:50
,year(now()) AS 年 #2017
,month(now()) AS 月 #11
,day(now()) AS 日 #13
,hour(now()) AS 小时 #17
,minute(now()) AS 分钟 #46
,second(now()) AS 秒 #50
,microsecond(now()) AS 微秒 #0
,quarter(now()) AS 季度 #4
,week(now()) AS 周 #46
;
(2). 时间截取函数:Extract()
SELECT now() #2017-11-13 18:21:06
,extract(year from now()) AS 年 #2017
,extract(month from now()) AS 月 #11
,extract(day from now()) AS 日 #13
,extract(hour from now()) AS 时 #18
,extract(minute from now()) AS 分 #21
,extract(second from now()) AS 秒 #6
,extract(microsecond from now()) AS 微秒 #0
,extract(quarter from now()) AS 季度 #4
,extract(week from now()) AS 周 #46
,extract(year_month from now()) #201711
,extract(day_hour from now()) #18
,extract(day_minute from now()) #1821
,extract(day_second from now()) #182106
,extract(day_microsecond from now()) #182106000000
,extract(hour_minute from now()) #1821
,extract(hour_second from now()) #182106
,extract(hour_microsecond from now()) #182106000000
,extract(minute_second from now()) #2106
,extract(minute_microsecond from now()) #2106000000
,extract(second_microsecond from now()) #6000000
;
(3). dayof... 函数:dayofweek(), dayofmonth(), dayofyear()
SELECT now() #2017-11-13 18:34:02
,dayofweek(now()) AS 本周中第几天 #2(1 = Sunday, 2 = Monday, ..., 7 = Saturday)
,dayofmonth(now()) AS 本月中第几天 #13
,dayofyear(now()) AS 本年中第几天 #317
;
(4). week... 函数:week(), weekofyear(), dayofweek(), weekday(), yearweek()
SELECT now() #2017-11-13 19:10:15
,week(now()) #46
,week(now(),3) #46
,weekofyear(now()) #46
,dayofweek(now()) #2
,weekday(now()) #0
,yearweek(now()) #201746
;
#MySQL week() 函数,可以有两个参数。 weekofyear() 和 week() 一样,都是计算“某天”是位于一年中的第几周。 weekofyear(@dt) 等价于 week(@dt,3)。
#MySQL weekday() 函数和 dayofweek() 类似,都是返回“某天”在一周中的位置。
#不同点在于参考的标准, weekday:(0 = Monday, 1 = Tuesday, ..., 6 = Sunday); dayofweek:(1 = Sunday, 2 = Monday, ..., 7 = Saturday)
#MySQL yearweek() 函数,返回 year(2008) + week 位置(31)。
(5). MySQL 返回星期和月份名称函数:dayname(), monthname()
SELECT now() #2017-11-13 19:14:11
,dayname(now()) #Monday
,monthname(now()) #November
;
(6). MySQL 返回月份中的最后一天函数:last_day()
SELECT last_day('2008-02-01'); #2008-02-29
SELECT last_day('2008-08-08'); #2008-08-31
last_day() 函数非常有用,比如我想得到当前月份中有多少天,可以这样来计算:
mysql> SELECT now(), day(last_day(now())) AS days;
+---------------------+------+
| now() | days |
+---------------------+------+
| 2017-11-13 19:16:07 | 30 |
+---------------------+------+
---------------------------------------------------------------------------------------------------------------------------------
三、 MySQL 时间计算
(2). MySQL 时间加 date_add()
SELECT now() #2017-11-13 18:04:03
,DATE_ADD(now(), interval 1 day) AS 加1天 #2017-11-14 18:04:03
,DATE_ADD(now(), interval 1 hour) AS 加1小时 #2017-11-13 19:04:03
,DATE_ADD(now(), interval 1 minute) AS 加1分钟 #2017-11-13 18:05:03
,DATE_ADD(now(), interval 1 second) AS 加1秒 #2017-11-13 18:04:04
,DATE_ADD(now(), interval 1 microsecond) AS 加1毫秒 #2017-11-13 18:04:03.000001
,DATE_ADD(now(), interval 1 week) AS 加1周 #2017-11-20 18:04:03
,DATE_ADD(now(), interval 1 month) AS 加1月 #2017-12-13 18:04:03
,DATE_ADD(now(), interval 1 quarter) AS 加1季 #2018-02-13 18:04:03
,DATE_ADD(now(), interval 1 year) AS 加1年 #2018-11-13 18:04:03
;
(2). MySQL 时间减 date_sub()
SELECT now() #2017-11-13 18:02:07
,DATE_SUB(now(), interval 1 day) AS 减1天 #2017-11-12 18:02:07
,DATE_SUB(now(), interval 1 hour) AS 减1小时 #2017-11-13 17:02:07
,DATE_SUB(now(), interval 1 minute) AS 减1分钟 #2017-11-13 18:01:07
,DATE_SUB(now(), interval 1 second) AS 减1秒 #2017-11-13 18:02:06
,DATE_SUB(now(), interval 1 microsecond) AS 减1毫秒 #2017-11-13 18:02:06.999999
,DATE_SUB(now(), interval 1 week) AS 减1周 #2017-11-06 18:02:07
,DATE_SUB(now(), interval 1 month) AS 减1月 #2017-10-13 18:02:07
,DATE_SUB(now(), interval 1 quarter) AS 减1季 #2017-08-13 18:02:07
,DATE_SUB(now(), interval 1 year) AS 减1年 #2016-11-13 18:02:07
;
(3). MySQL 增加时间间隔 date_add()
MySQL adddate(), addtime()函数,可以用 date_add() 来替代。下面是 date_add() 实现 addtime() 功能示例:
分别增加了“1小时 15分 30秒” 和 “1天 1小时 15分 30秒”
SELECT now() #2017-11-13 19:45:33
,date_add(now(), interval '01:15:30' hour_second) #2017-11-13 21:01:03
,date_add(now(), interval '1 01:15:30' day_second) #2017-11-14 21:01:03
;
(4). MySQL 减去时间间隔 date_sub()
MySQL subdate(), subtime()函数,可以用 date_sub() 来替代。
mysql> SELECT date_sub('1998-01-01 00:00:00', interval '1 1:1:1' day_second);
+----------------------------------------------------------------+
| date_sub('1998-01-01 00:00:00', interval '1 1:1:1' day_second) |
+----------------------------------------------------------------+
| 1997-12-30 22:58:59 |
+----------------------------------------------------------------+
(5). MySQL 另类日期函数:period_add(P,N), period_diff(P1,P2)
函数参数“P” 的格式为“YYYYMM” 或者 “YYMM”,第二个参数“N” 表示增加或减去 N month(月)。
1. MySQL period_add(P,N):日期加/减去N月。
mysql> select period_add(200808,2), period_add(20080808,-2)
+----------------------+-------------------------+
| period_add(200808,2) | period_add(20080808,-2) |
+----------------------+-------------------------+
| 200810 | 20080806 |
+----------------------+-------------------------+
2. MySQL period_diff(P1,P2):日期 P1-P2,返回 N 个月。
mysql> select period_diff(200808, 200801);
+-----------------------------+
| period_diff(200808, 200801) |
+-----------------------------+
| 7 |
+-----------------------------+
(6). MySQL 日期、时间相减函数:datediff(date1,date2), timediff(time1,time2)
1. MySQL datediff(date1,date2):两个日期相减 date1 - date2,返回天数。
SELECT now() #2017-11-13 20:16:32
,submit_time #2017-11-02 16:52:52
,datediff(now(),submit_time) #11
,datediff('2008-08-08', '2008-08-01') #7
,datediff('2008-08-01', '2008-08-08') #-7
FROM table_name WHERE is_deleted = 'n' AND number = 030734;
2. MySQL timediff(time1,time2):两个日期相减 time1 - time2,返回 time 差值。
select timediff('2008-08-08 08:08:08', '2008-08-08 00:00:00'); #08:08:08
select timediff('08:08:08', '00:00:00'); #08:08:08
------------------------------------------------------------------------------------------------------------------------------
四、MySQL 日期转换函数、时间转换函数
(1). MySQL (时间、秒)转换函数:time_to_sec(time), sec_to_time(seconds)
select time_to_sec('01:00:05'); -- 3605
select sec_to_time(3605); -- '01:00:05'
(2). MySQL (日期、天数)转换函数:to_days(date), from_days(days)
select to_days('0000-00-00'); -- 0
select to_days('2008-08-08'); -- 733627
select from_days(0); -- '0000-00-00'
select from_days(733627); -- '2008-08-08'
(3). MySQL Str to Date (字符串转换为日期)函数:str_to_date(str, format)
select str_to_date('08/09/2008', '%m/%d/%Y'); -- 2008-08-09
select str_to_date('08/09/08' , '%m/%d/%y'); -- 2008-08-09
select str_to_date('08.09.2008', '%m.%d.%Y'); -- 2008-08-09
select str_to_date('08:09:30', '%h:%i:%s'); -- 08:09:30
select str_to_date('08.09.2008 08:09:30', '%m.%d.%Y %h:%i:%s'); -- 2008-08-09 08:09:30
(4). MySQL Date/Time to Str(日期/时间转换为字符串)函数:date_format(date,format), time_format(time,format)
mysql> select date_format('2008-08-08 22:23:00', '%W %M %Y');
+------------------------------------------------+
| date_format('2008-08-08 22:23:00', '%W %M %Y') |
+------------------------------------------------+
| Friday August 2008 |
+------------------------------------------------+
mysql> select date_format('2008-08-08 22:23:01', '%Y%m%d%H%i%s');
+----------------------------------------------------+
| date_format('2008-08-08 22:23:01', '%Y%m%d%H%i%s') |
+----------------------------------------------------+
| 20080808222301 |
+----------------------------------------------------+
mysql> select time_format('22:23:01', '%H.%i.%s');
+-------------------------------------+
| time_format('22:23:01', '%H.%i.%s') |
+-------------------------------------+
| 22.23.01 |
+-------------------------------------+
MySQL 日期、时间转换函数:date_format(date,format), time_format(time,format) 能够把一个日期/时间转换成各种各样的字符串格式。它是 str_to_date(str,format) 函数的一个逆转换。
select date_format(now(),'%Y-%M');#2018-April
select date_format(now(),'%y-%m');#18-04
select date_format(now(),'%Y-%m'); #2018-04
(5). MySQL 获得国家地区时间格式函数:get_format()
MySQL get_format() 语法:
get_format(date|time|datetime, 'eur'|'usa'|'jis'|'iso'|'internal'
MySQL get_format() 用法的全部示例:
select get_format(date,'usa') ; -- '%m.%d.%Y'
select get_format(date,'jis') ; -- '%Y-%m-%d'
select get_format(date,'iso') ; -- '%Y-%m-%d'
select get_format(date,'eur') ; -- '%d.%m.%Y'
select get_format(date,'internal') ; -- '%Y%m%d'
select get_format(datetime,'usa') ; -- '%Y-%m-%d %H.%i.%s'
select get_format(datetime,'jis') ; -- '%Y-%m-%d %H:%i:%s'
select get_format(datetime,'iso') ; -- '%Y-%m-%d %H:%i:%s'
select get_format(datetime,'eur') ; -- '%Y-%m-%d %H.%i.%s'
select get_format(datetime,'internal') ; -- '%Y%m%d%H%i%s'
select get_format(time,'usa') ; -- '%h:%i:%s %p'
select get_format(time,'jis') ; -- '%H:%i:%s'
select get_format(time,'iso') ; -- '%H:%i:%s'
select get_format(time,'eur') ; -- '%H.%i.%s'
select get_format(time,'internal') ; -- '%H%i%s'
MySQL get_format() 函数在实际中用到机会的比较少。
(6). MySQL 拼凑日期、时间函数:makdedate(year,dayofyear), maketime(hour,minute,second)
select makedate(2001,31); -- '2001-01-31'
select makedate(2001,32); -- '2001-02-01'
select maketime(12,15,30); -- '12:15:30'
----------------------------------------------------------------------------------------------------------------------------------
五、MySQL 时间戳(Timestamp)函数
1. MySQL 获得当前时间戳函数:current_timestamp, current_timestamp()
mysql> select current_timestamp, current_timestamp();
+---------------------+---------------------+
| current_timestamp | current_timestamp() |
+---------------------+---------------------+
| 2008-08-09 23:22:24 | 2008-08-09 23:22:24 |
+---------------------+---------------------+
2. MySQL (Unix 时间戳、日期)转换函数:
unix_timestamp(),
unix_timestamp(date),
from_unixtime(unix_timestamp),
from_unixtime(unix_timestamp,format)
下面是示例:
select unix_timestamp(); -- 1218290027
select unix_timestamp('2008-08-08'); -- 1218124800
select unix_timestamp('2008-08-08 12:30:00'); -- 1218169800
select from_unixtime(1218290027); -- '2008-08-09 21:53:47'
select from_unixtime(1218124800); -- '2008-08-08 00:00:00'
select from_unixtime(1218169800); -- '2008-08-08 12:30:00'
select from_unixtime(1218169800, '%Y %D %M %h:%i:%s %x'); -- '2008 8th August 12:30:00 2008'
3. MySQL 时间戳(timestamp)转换、增、减函数:
timestamp(date) -- date to timestamp
timestamp(dt,time) -- dt + time
timestampadd(unit,interval,datetime_expr) --
timestampdiff(unit,datetime_expr1,datetime_expr2) --
请看示例部分:
select timestamp('2008-08-08'); -- 2008-08-08 00:00:00
select timestamp('2008-08-08 08:00:00', '01:01:01'); -- 2008-08-08 09:01:01
select timestamp('2008-08-08 08:00:00', '10 01:01:01'); -- 2008-08-18 09:01:01
select timestampadd(day, 1, '2008-08-08 08:00:00'); -- 2008-08-09 08:00:00
select date_add('2008-08-08 08:00:00', interval 1 day); -- 2008-08-09 08:00:00
MySQL timestampadd() 函数类似于 date_add()。
select timestampdiff(year,'2002-05-01','2001-01-01'); -- -1
select timestampdiff(day ,'2002-05-01','2001-01-01'); -- -485
select timestampdiff(hour,'2008-08-08 12:00:00','2008-08-08 00:00:00'); -- -12
select datediff('2008-08-08 12:00:00', '2008-08-01 00:00:00'); -- 7
MySQL timestampdiff() 函数就比 datediff() 功能强多了,datediff() 只能计算两个日期(date)之间相差的天数。
-----------------------------------------------------------------------------------------------------------------------------------------
六、MySQL 时区(timezone)转换函数
convert_tz(dt,from_tz,to_tz)
select convert_tz('2008-08-08 12:00:00', '+08:00', '+00:00'); -- 2008-08-08 04:00:00
时区转换也可以通过 date_add, date_sub, timestampadd 来实现。
select date_add('2008-08-08 12:00:00', interval -8 hour); -- 2008-08-08 04:00:00
select date_sub('2008-08-08 12:00:00', interval 8 hour); -- 2008-08-08 04:00:00
select timestampadd(hour, -8, '2008-08-08 12:00:00'); -- 2008-08-08 04:00:00
通过时间戳来转换
SELECT a FROM test WHERE( UNIX_TIMESTAMP(start_time)-3600*24) > UNIX_TIMESTAMP('$now')
MySQL中的UNIX_TIMESTAMP函数有两种类型供调用
1 无参数调用:UNIX_TIMESTAMP() 返回值:自'1970-01-01 00:00:00'的到当前时间的秒数差 例子:SELECT UNIX_TIMESTAMP() => 1339123415
2 有参数调用:UNIX_TIMESTAMP(date) 其中date可以是一个DATE字符串,一个DATETIME字符串,一个TIMESTAMP或者一个当地时间的YYMMDD或YYYMMDD格式的数字 返回值:自'1970-01-01 00:00:00'与指定时间的秒数差
SELECT UNIX_TIMESTAMP(NOW()) => 1339123415 注:NOW()的返回值是一个DATETIME字符串格式
---------------------------------------------------------------------------------------------------------------------------------------
七、TIMESTAMP和DATETIME
(1)TIMESTAMP和DATETIME的相同点:两者都可用来表示YYYY-MM-DD HH:MM:SS[.fraction]类型的日期。
(2)TIMESTAMP和DATETIME的不同点:两者的存储方式不一样
对于TIMESTAMP,它把客户端插入的时间从当前时区转化为UTC(世界标准时间)进行存储。查询时,将其又转化为客户端当前时区进行返回。
而对于DATETIME,不做任何改变,基本上是原样输入和输出。
下面,我们来验证一下
1. 首先创建两种测试表,一个使用timestamp格式,一个使用datetime格式。
mysql> create table test(id int,hiredate timestamp);
Query OK, 0 rows affected (0.01 sec)
mysql> insert into test values(1,'20151208000000');
Query OK, 1 row affected (0.00 sec)
mysql> create table test1(id int,hiredate datetime);
Query OK, 0 rows affected (0.01 sec)
mysql> insert into test1 values(1,'20151208000000');
Query OK, 1 row affected (0.00 sec)
mysql> select * from test;
+------+---------------------+
| id | hiredate |
+------+---------------------+
| 1 | 2015-12-08 00:00:00 |
+------+---------------------+
1 row in set (0.01 sec)
mysql> select * from test1;
+------+---------------------+
| id | hiredate |
+------+---------------------+
| 1 | 2015-12-08 00:00:00 |
+------+---------------------+
1 row in set (0.00 sec)
两者输出是一样的。
2. 其次修改当前会话的时区
mysql> show variables like '%time_zone%';
+------------------+--------+
| Variable_name | Value |
+------------------+--------+
| system_time_zone | CST |
| time_zone | SYSTEM |
+------------------+--------+
2 rows in set (0.00 sec)
mysql> set time_zone='+0:00';
Query OK, 0 rows affected (0.00 sec)
mysql> select * from test;
+------+---------------------+
| id | hiredate |
+------+---------------------+
| 1 | 2015-12-07 16:00:00 |
+------+---------------------+
1 row in set (0.00 sec)
mysql> select * from test1;
+------+---------------------+
| id | hiredate |
+------+---------------------+
| 1 | 2015-12-08 00:00:00 |
+------+---------------------+
1 row in set (0.01 sec)
上述“CST”指的是MySQL所在主机的系统时间,是中国标准时间的缩写,China Standard Time UT+8:00
通过结果可以看出,test中返回的时间提前了8个小时,而test1中时间则不变。这充分验证了两者的区别。
3. 两者所能存储的时间范围不一样
timestamp所能存储的时间范围为:'1970-01-01 00:00:01.000000' 到 '2038-01-19 03:14:07.999999'。
datetime所能存储的时间范围为:'1000-01-01 00:00:00.000000' 到 '9999-12-31 23:59:59.999999'。
总结:TIMESTAMP和DATETIME除了存储范围和存储方式不一样,没有太大区别。当然,对于跨时区的业务,TIMESTAMP更为合适。