SQL Server provides a number of options you can use to format a date/time string. One of the first considerations is the actual date/time needed. The most common is the current date/time using getdate(). This provides the current date and time according to the server providing the date and time. If a universal date/time is needed, then getutcdate() should be used. To change the format of the date, you convert the requested date to a string and specify the format number corresponding to the format needed. Below is a list of formats and an example of the output:
DATE FORMATS | ||
Format # | Query(Current date : 09/10/2009 | Sample |
1 | select convert(varchar, getdate(), 1) | 09/10/09 |
2 | select convert(varchar, getdate(), 2) | 09.09.10 |
3 | select convert(varchar, getdate(), 3) | 10/09/09 |
4 | select convert(varchar, getdate(), 4) | 10.09.09 |
5 | select convert(varchar, getdate(), 5) | 10-09-09 |
6 | select convert(varchar, getdate(), 6) | 10 Sep 09 |
7 | select convert(varchar, getdate(), 7) | Sep 10, 09 |
10 | select convert(varchar, getdate(), 10) | 09-10-09 |
11 | select convert(varchar, getdate(), 11) | 09/09/10 |
101 | select convert(varchar, getdate(), 101) | 09/10/2009 |
102 | select convert(varchar, getdate(), 102) | 2009.09.10 |
103 | select convert(varchar, getdate(), 103) | 10/09/2009 |
104 | select convert(varchar, getdate(), 104) | 10.09.2009 |
105 | select convert(varchar, getdate(), 105) | 10-09-2009 |
106 | select convert(varchar, getdate(), 106) | 10 Sep 2009 |
107 | select convert(varchar, getdate(), 107) | Sep 10, 2009 |
110 | select convert(varchar, getdate(), 110) | 09-10-2009 |
111 | select convert(varchar, getdate(), 111) | 2009/09/10 |
Time Format:
Time Format | ||
8 or 108 | select convert(varchar, getdate(),8) | 00:38:54 |
9 or 109 | select convert(varchar, getdate(), 9) | Sep 10 2009 12:38:54:840AM |
14 or 114 | select convert(varchar, getdate(), 14) | 00:38:54:840 |
You can also format the date or time without dividing characters, as well as concatenate the date and time string:
Sample Statement | Output |
select replace(convert(varchar, getdate(),101),’/',”) | 09102009 |
select replace(convert(varchar, getdate(),101),’/',”) + replace(convert(varchar, getdate(),108),’:',”) | 09102009004426 |
No comments:
Post a Comment