SQL Server date formatting

The getdate() function is often used in SQL Server to obtain the current time, which is accurate to seconds. For example, query: select getdate(); The result is: 2016-06-24 11:36:01.120. But most of the time we only need to know the date, and it is the date in the specified format. At this point you need to use the CONVERT() function.

 

1. Definition and usage of CONVERT() function:
CONVERT() function is a general function to convert date to new data type.
The CONVERT() function can display date/time data in different formats.

 

2. The syntax of the CONVERT() function:
CONVERT(data_type(length), data_to_be_converted, style)
data_type(length) specifies the target data type (with an optional length). data_to_be_converted contains the value that needs to be converted. style specifies the output format of the date/time.


3. The value of the third parameter style of the CONVERT() function :

Style ID

standard

Style format

Example output

CONVERT(VARCHAR(30),GETDATE(),id);

100 / 0

Default

mon dd yyyy hh:miAM (or PM )

06 24 2016 11:43AM

101/1

USA

mm/dd/yy

101:06/24/2016

1: 06/24/16

102/2

ANSI

yy.mm.dd

102:2016.06.24

2: 16.06.24

103/3

British/French

dd/mm/yy

103: 24/06/2016

3: 24/06/16

104/4

German

dd.mm.yy

104: 24.06.2016

4: 24.06.16

105/5

Italian

dd-mm-yy

105: 24-06-2016

5: 24-06-16

106/6

 

dd mon yy

106: 24 06 2016

6: 24 06 16

107/7

 

Mon dd, yy

107: 06 24, 2016

7: 06 24, 16

108/8

 

hh:mm:ss

11:55:15

109/9

Default + milliseconds

mon dd yyyy hh:mi:ss:mmmAM (or PM )

06 24 2016 11:56:19:250AM

110/10

USA

mm-dd-yy

110: 06-24-2016

10: 06-24-16

111/11

JAPAN

yy/mm/dd

111: 2016/06/24

11: 16/06/24

112/12

ISO

yymmdd

112: 20160624

12: 160624

113/13

Europe Default + milliseconds

dd mon yyyy hh:mm:ss:mmm(24h)

24 06 2016 12:01:02:610

114/14

 

hh:mi:ss:mmm(24h)

12:01:46:353

120/20

 

yyyy-mm-dd hh:mi:ss(24h)

2016-06-24 12:02:40

121/21

 

yyyy-mm-dd hh:mi:ss.mmm(24h)

2016-06-24 12:03:34.793

126

 

yyyy-mm-ddThh:mm:ss.mmm (no spaces)

126: 2016-06-24T12:04:33.930

130

 

dd mon yyyy hh:mi:ss:mmmAM

19 ????? 1437 12:08:31:213PM

131

 

dd/mm/yy hh:mi:ss:mmmAM

19/09/1437 12:08:31:213PM

 

4、补充:
a、几个特殊的:
select getdate():2016-06-24 12:21:08.623(convert函数中121的格式)
select convert(varchar(10),getdate()):06 24 2016(那种格式都不是,100/0的格式有小时和分钟)


b、当CONVERT()函数传入不存在的Style ID则会报错,比如查询“SELECT CONVERT(VARCHAR(30),GETDATE(),26)”就会报错:从 datetime 转换为字符串时,26 不是有效的样式号。


c、这里的varchar(30),指的是获取的字符段的个数(为了让所有的字符串都显示出来所以定义的比较大),比如原本是2016-06-24 12:03:34.793,为了只获取2016-06-24字段,算了下,一共10个字符,所以选择varchar(10),又比如为varchar(7),则为2016-06,又比如:varchar(4),则为2016了。

参考链接:
1、百度知道:SQL获取日期的所有格式:http://zhidao.baidu.com/link?url=-f3UwbhFjUct6VoRS1B8ASeeYIiQd4PZazJWwtjZbE9hyQ0sAu9Suw-WYwI0YUJZHls6L9_QnFphUvZjv9Up_K
2、W3School:SQL Server CONVERT() 函数:http://www.w3school.com.cn/sql/func_convert.asp

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326780904&siteId=291194637