MySQL 获得当前日期时间 常用函数

MySQL 获得当前日期时间 常用函数

1. 获得当前日期+时间(date + time)函数:now()
	 mysql> select now();
	+---------------------+
	| now()               |
	+---------------------+
	| 2020-07-24 17:28:15 |
	+---------------------+

格式化输出日期 date_format(date, format)

  • 注: date:时间字段
    format:日期格式

格式化输出 如:2020-07-24

mysql> select date_format(now(),'%y-%m-%d') as 当前日期;
+--------------+
| 当前日期     |
+--------------+
| 20-07-24     |
+--------------+
  • 获取当前日期可直接使用curdate()
2.获取当前时间(time)函数:curtime()
mysql> select curtime();
+-----------+
| curtime() |
+-----------+
| 17:29:43  |
+-----------+

格式化输出同上

mysql> select date_format(now(),'%H:%i:%s') as 当前时间;
+--------------+
| 当前时间     |
+--------------+
| 17:07:09     |
  • 注:%H表示24小时制,%i 两位数字形式的分钟。

3.获取当前时间戳 unix_timestamp()

mysql> select unix_timestamp(now())as 当前时间戳;
+-----------------+
| 当前时间戳      |
+-----------------+
|      1595585123 |
+-----------------+
  • 单位为秒/s

4.获取两日期间隔的天数 datediff ()

mysql> select datediff(curdate(),'1998-04-10');
+----------------------------------+
| datediff(curdate(),'1998-04-10') |
+----------------------------------+
|                             8144 |
+----------------------------------+

我们可以利用此功能可以算出年龄(age),如:

mysql> select datediff(curdate(),'1998-04-10') div 365 as '年龄(age)';
+-------------+
| 年龄(age)   |
+-------------+
|          22 |
+-------------+

希望能帮助到小伙伴们,如果能还能点个赞,那就是对我最大的鼓励

猜你喜欢

转载自blog.csdn.net/Jerry_233/article/details/107566936