MySQL学习记录--生成时间日期数据

  时间数据格式组件:

组件 定义 范围
YYYY 年份,包括世纪 1000~9999
MM 月份 01(January)~12(December)
DD 01~31
HH 小时 00~23
HHH 小时 -838~838
MI 分钟 00~59
SS 00~59

  日期数据部件:

类型 默认格式
Date YYYY-MM-DD
Datetime YYYY-MM-DD HH:MI:SS
Timestamp YYYY-MM-DD HH:MI:SS
Time HHH:MI:SS

一、产生时间日期的函数

   1、str_to_date()   格式化输出时间日期

    函数str_to_date()可以格式化输出时间日期,该函数可识别30多种格式部件(format component)。

    举例:将字符串"September 02, 2016" 输出为日期数据

mysql> select str_to_date('September 02,2016', '%M %d,%Y') as date;    -- 注:str_to_date()的参数一与参数二的格式应一致
+------------+
| date       |
+------------+
| 2016-09-02 |
+------------+
1 row in set (0.00 sec)

  附:日期格式部件

格式部件 描述
%M 月名称(January)~(December)
%m 月序号(01~12)
%d 日序号(01~31)
%j 日在一年中的序号(001~366)
%W 星期名称(星期日~星期六)
%Y 4位数字表示的年份
%y 两位数字表示的年份
%H 小时(00~23)
%h 小时(01~12)
%i 分钟(00~59)
%f 微秒(000000~999999)
%s 秒钟(00~59)
%p A.M.或P.M.

  2、生成当前时间日期函数

    下列函数将按照所返回时间类型的默认格式返回当前日期或时间值。

mysql> select current_date(), current_time(), current_timestamp();
+----------------+----------------+---------------------+
| current_date() | current_time() | current_timestamp() |
+----------------+----------------+---------------------+
| 2016-11-30     | 14:44:44       | 2016-11-30 14:44:44 |
+----------------+----------------+---------------------+
1 row in set (0.00 sec)

   在Oracle数据库包含current_date()和current_time()函数,但没有current_time(),而SQL Server则只包含current_timestamp()函数。

原文地址:https://www.cnblogs.com/technologylife/p/6117794.html