SQL中的時間函式

2021-10-04 06:25:19 字數 2401 閱讀 5216

1、常用:

year()、month()、day()、minute()、second()、分別取日期的對應部分

curdate()——2020-3-22 取當前日期

curtime()——22:47:37 取當前時間

weekofyear()當前時刻是全年中的第幾周

dayofweek() 當天是一周內的週幾

2、格式轉換:

(1)、date_format函式

date_format(「2019-12-25 22:47:37」,"%y-%m-%d")

主題格式描述年

%y4位數的年月%b

月份對應的英文縮寫月%m

月份對應的英文全稱月%m

01-12的月月%c

1-12的月份數值日%d

01-31的某月裡面的第幾天日%e

1-31的某月裡面的第幾天日%d

用th字尾表示某月中的第幾天日%j

001-366的一年中的第幾天周%a

星期幾對應的英文縮寫周%w

星期幾對應的英文全稱時%h

00-23的小時時%h

01-12的小時分%i

00-59的分鐘秒%s

秒(00-59)秒%f

微秒時分秒

%t返回當前的時分秒, 24-小時 (hh:mm:ss)

(2)、extract(unit from datetime)

extract(year from 「2019-12-25 22:47:37」)

unit

說明year

年month

月day

日hour

小時minute

分鐘second

秒week

週數,全年第幾周

(3)、 時間戳與時間互相轉換

--時間戳轉時間

select

distinct from_unixtime(

1441565203

,'yyyy/mm/dd hh:mm:ss'

)from test_date;

--時間轉時間戳

select

distinct unix_timestamp(

'20200307 16:23:03'

)from test_date;

-- 預設格式為「yyyy-mm-dd hh:mm:ss「

select

distinct unix_timestamp(

'20200307 16:23:03'

,'yyyymmdd hh:mm:ss'

)from test_date;

(4)、 帶槓與不帶槓轉換
-- 20181205轉成2018-12-05

select from_unixtime(unix_timestamp(『20181205』,『yyyymmdd』)

,『yyyy-mm-dd』)

from dual;

-- 2018-12-05轉成20181205

select from_unixtime(unix_timestamp(『2018-12

-05』,『yyyy-mm-dd』)

,『yyyymmdd』)

from dual;

#20181205轉成2018-12-05

select concat(substr(『20181205』,1,

4),』-』,substr(『20181205』,5,

2),』-』,substr(『20181205』,7,

2))from dual;

#2018-12-05轉成20181205

select concat(substr(『2018-12

-05』,1,

4),substr(『2018-12

-05』,6,

2),substr(『2018-12

-05』,9,

2))from dual;

3、時間運算

(1)、日期向後偏移

date_add(date,interval num unit)

date_add(「2019-01-01」,interval 7 year)

interval是乙個固定的引數

unit與extract中的一致

num可以是負數,則表示向前偏移

(2)、日期向前偏移

date_sub(date,interval num unit)

date_sub(「2019-01-01」,interval 7 year)

(3)、兩日期做差

datediff(end_date,start_date)

datediff(「2019-01-07」,「2019-01-01」),返回結果為6

SQL中的時間函式

sql資料庫中有各種不同的函式,下面為您介紹sql中的時間函式,如果您是才接觸sql的新手,不妨一看,相信會對您有所幫助。getdate 返回當前系統日期和時間。dateadd 在向指定日期加上一段時間的基礎上,返回新的 datetime 值。dateadd datepart number,date...

SQL的時間函式

當我們處理日期時,最難的任務恐怕是確保所插入的日期的格式,與資料庫中日期列的格式相匹配。只要資料報含的只是日期部分,執行查詢就不會出問題。但是,如果涉及時間,情況就有點複雜了。在討論日期查詢的複雜性之前,我們先來看看最重要的內建日期處理函式。now 函式返回當前的日期和時間。下面是 select 語...

sql中關於日期 時間的函式

1,add months 列名,n 將給定的日期增加n個月,例如 select add months hiredate,2 as newdate from emp 就是將hiredate這個日期增加2個月 那如果我要減去n個月呢?n n就可以了啊 2,last day 顯示指定月份的最後一天,例如 ...