目录
1. 获取系统日期、时间
1.1 now()
now([fsp]):返回系统当前的日期和时间(fsp指定小数秒的精度,取值0-6)。
1. select now();
2. select now(2); # 指定小数秒的精度
3. select now()+0; # now()+0显示格式是‘YYYYMMDDHHMMSS’
->
1. 2020-02-18 19:36:39
2. 2020-02-18 19:36:39.46
3. 20200218193639
1.2 sysdate()
sysdate([fsp]):返回系统当前的日期和时间,但一般用now()。
sysdate()返回的是函数执行时的时间。
now()返回的是语句执行时的时间。
1. select sysdate();
2. select now(),sleep(2),now();
3. select sysdate(),sleep(2),sysdate();
->
1. 2020-02-18 19:36:39
2. 2020-02-18 19:42:11 0 2020-02-18 19:42:11
3. 2020-02-18 19:42:13 0 2020-02-18 19:42:15
1.3 curdate()
curdate():返回当前日期,只包含年月日。
1. select curdate();
2. select curdate()+2; # 当前日期加2天
->
1. 2020-02-18
2. 20200220
1.4 curtime()
curtime([fsp]):返回当前时间,只包含时分秒(fsp指定小数秒的精度,取值0-6)。
1. select curtime();
2. select curtime(6);
3. select curtime()+2; # 加2秒
->
1. 19:49:39
2. 19:49:39.354219
3. 194941
2. 日期、时间相减
2.1 datediff()
datediff(expr1,expr2):返回两个日期相减的天数(expr1 - expr2)。
select datediff('2020-04-18 10:00:00','2010-02-18');
->
3712
2.2 timediff()
timediff(expr1, expr2):返回两个时间相减的时间数(expr1 − expr2),两个参数类型必须相同。范围在-838:59:59到838:59:59。
timestampdiff(unit,begin,end):根据unit单位返回时间差。
1. select timediff('18:32:59','00:1:00');
2. select timediff('2020-02-18 10:00:00','10:00:00'); # 如果传递两个不同类型的参数,返回null
3. select timediff('2020-02-18 10:00:00','2020-02-15');
4. select timediff('2020-02-18 10:00:00',null);
5. select timediff('2020-04-18 10:00:00','2020-02-18 10:00:00'); # timediff函数返回的结果是一个time值,范围是从-838:59:59到838:59:59。当范围超过的时候,MySQL会截断结果。
6. select timestampdiff(hour,'2020-04-18 10:00:00','2020-02-18 10:00:00') # 解决范围超过截断的问题。
->
1. 18:31:59
2. null
3. null
4. null
5. 838:59:59
6. -1440