SQL Convert的用法及獲取時間,以及用substring獲取相應的日期,小時,分鐘

 語法 
CONVERT ( data type, expression  [format-style ] )

參數 
data type    表達式將轉換成的數據類型。

expression    要轉換的表達式。

format
-style    對於將字符串轉換爲日期或時間數據類型以及相反的轉換過程,format-style 是描述要使用的日期格式字符串的樣式代碼。 format-style 參數的值具有下列含義:不含世紀 (yy)  含世紀 (yyyy)  輸出  -  0 或 100  Mmm dd yyyy hh:nn:ss:sss AM(或 PM)  

 

使用 CONVERT:

CONVERT (data_type[(length)], expression [, style])


select CONVERT(varchar, getdate(), 120 ) 
2004-09-12 11:06:08 

select replace(replace(replace(CONVERT(varchar, getdate(), 120 ),/'-/',/'/'),/' /',/'/'),/':/',/'/') 
20040912110608 

select CONVERT(varchar(12) , getdate(), 111 ) 
2004/09/12 

select CONVERT(varchar(12) , getdate(), 112 ) 
20040912 

select CONVERT(varchar(12) , getdate(), 102 ) 
2004.09.12 

select CONVERT(varchar(12) , getdate(), 101 ) 
09/12/2004 

select CONVERT(varchar(12) , getdate(), 103 ) 
12/09/2004 

select CONVERT(varchar(12) , getdate(), 104 ) 
12.09.2004 

select CONVERT(varchar(12) , getdate(), 105 ) 
12-09-2004 

select CONVERT(varchar(12) , getdate(), 106 ) 
12 09 2004 

select CONVERT(varchar(12) , getdate(), 107 ) 
09 12, 2004 

select CONVERT(varchar(12) , getdate(), 108 ) 
11:06:08 

select CONVERT(varchar(12) , getdate(), 109 ) 
09 12 2004 1 

select CONVERT(varchar(12) , getdate(), 110 ) 
09-12-2004 

select CONVERT(varchar(12) , getdate(), 113 ) 
12 09 2004 1 

select CONVERT(varchar(12) , getdate(), 114 ) 
11:06:08.177

下面是Substring截取

select substring(convert(varchar,convert(datetime,getdate(),120),120),12,5)

得到的是當前時間:18:08

如果想獲取日期,改後面(12,5)相應的值

當然,還有另一種方法,如

SELECT DATEPART(hh,GETDATE()) //當前小時
SELECT DATEPART(DD,GETDATE()) //當前分鐘


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章