SQL server獲取當前時間的幾種

2022-02-26 21:31:24 字數 2461 閱讀 5273

1. 獲取當前日期

select getdate()

格式化:

select convert(varchar,getdate(),120) --2017-05-12 16:33:10

2. 獲取當前年  --2017

select datename(yyyy,getdate()) --2017

select datename(year,getdate()) --2017

select datepart(yyyy,getdate()) --2017

select datepart(year,getdate()) --2017

select year(getdate())--2017

3.獲取當前月 --05或5

select datename(mm,getdate()) --05

select datename(month,getdate()) --05

select datepart(mm,getdate()) --5

select datepart(month,getdate()) --5

select month(getdate()) --5

4.獲取當前日期 --07或7

select datename(day,getdate()-5) --7

select datename(d,getdate()-5) --7

select datename(dd,getdate()-5) --7

select datepart(d,getdate()-5) --7

select datepart(dd,getdate()-5) --7 

select datepart(day,getdate()-5) --7

select day(getdate()-5)

5. 獲取當前年月 --201705

select convert(varchar(6),getdate(),112) --201705

select convert(varchar(7),getdate(),120) --2017-05

6.獲取當前年月日 --20170512

select convert(varchar(8),getdate(),112) --20170512

select convert(varchar(10),getdate(),120) --2017-05-12

getdate() :獲取當前時間,時間格式預設。

datename:引數為兩個,取值區間 interval 和時間 date

date 就是時間;

interval  包括 年,月,日,星期等

e.g:

year 年;yyyy 年;yy 年;

quarter 季度;qq 季度 ;q 季度;

month 月(05);mm 月(05);m 月(05);

weekday 星期幾;dw 星期幾;w 星期幾;

week 一年的第幾周;wk 一年的第幾周;ww 一年的第幾周;isowk 一年的第幾周;isoww 一年的第幾周;iso_week 一年的第幾周;

day 天;dd 天;d 天;

dayofyear 一年的第幾天;dy 一年的第幾天;y 一年的第幾天;

hour 小時;hh 小時;

minute 分鐘;mi 分鐘;n 分鐘;

second 秒;ss 秒;s 秒;

mcs 微秒(略);microsecond 微秒(略);millisecond 毫秒(略);ms 毫秒(略) ; nanosecond 十億分之一秒(略);ns 十億分之一秒(略);

convert 函式轉換格式:主要注意第三個引數 date_style ;格式:select convert(varchar,getdate(),0)

最後的 date_style 可以有 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,100,

101,102,103,104,105,106,107,108,109,110,111,112,113,114,120,121,126,127,130,131等

常用的 20,23,24,102,111,112,120等;

示例:select convert(varchar,getdate(),20)  --2017-05-12 17:22:22

select convert(varchar,getdate(),23)  --2017-05-12

select convert(varchar,getdate(),24)  --17:23:42

select convert(varchar,getdate(),102) --2017.05.12

select convert(varchar,getdate(),111) --2017/05/12

select convert(varchar,getdate(),112) --20170512

**於

獲取當前時間

獲取日期 時間 datetime.now.tostring 2008 9 4 20 02 10 datetime.now.tolocaltime tostring 2008 9 4 20 12 12 獲取日期 datetime.now.tolongdatestring tostring 2008年9...

獲取當前時間

直接上可以執行的 檔案 獲取當前時間.cpp 方案 time 優點 僅使用c標準庫 缺點 只能精確到秒級 include time.h include stdio.h int main void 方案二getlocaltime 優點 能精確到毫秒級 缺點 使用了windows api include...

獲取當前時間

使用函式 date 實現 顯示的格式 年 月 日 小時 分鐘 妙 相關時間引數 a am 或是 pm a am 或是 pm d 幾日,二位數字,若不足二位則前面補零 如 01 至 31 d 星期幾,三個英文本母 如 fri f 月份,英文全名 如 january h 12 小時制的小時 如 01 至...