SQL Server : Datetime Format With Convert Function

We can use FORMAT() function to format DATE/TIME data value otherwise we can use CONVERT() function.

Working with date and time we often need the right format so the system doesn't read it as an error format. Because the form of writing the date/time really depends on the regional setting on the machine being used

The safest date format to use is YYYY-MM-dd or if included with time it becomes YYYY-MM-DD hh:mm:ss. This format can be read in various regional date settings.

The following data types in SQL Server related to date and time:


To change the date format in SQL Server we use the CONVERT function. The syntax used is as follows:

SELECT CONVERT (data_type(length)),Date, DateFormatCode)

  • Data_Type: complete data type with its size, we usually use the VARCHAR(length) data type as the result of the date format to be created.
  • Date: Date value to be formatted
  • DateFormatCode: The sequence code is a number that represents a specific date format.

Contoh:

SELECT CONVERT(VARCHARGETDATE() ,0) AS tanggal


List of DateFormatCode with how its result:

Date format optionSQL convert date output
0Dec 30 2021 12:38AM
112/30/2021
206.12.30
330/12/2021
430.12.06
530/12/2021
630-Dec-06
730-Dec-06
80:38:54
9Dec 30 2021 12:38:54:840AM
1012/30/2021
116/12/1930
1261230
1330 Dec 2021 00:38:54:840
1400:38:54:840
2030/12/2021 00:38
2138:54.8
2212/30/2021 0:38
2330/12/2021
240:38:54
2538:54.8
262021-30-12 00:38:54.840
2738:54.8
2812-2021-30 00:38:54.840
2938:54.8
3030-2021-12 00:38:54.840
312021-30-12
3212/30/2021
3312-2021-30
3430/12/2021
3530-2021-12
100Dec 30 2021 12:38AM
10112/30/2021
1022021.12.30
10330/12/2021
10430.12.2021
10530/12/2021
10630-Dec-06
10730-Dec-06
1080:38:54
109Dec 30 2021 12:38:54:840AM
11012/30/2021
11130/12/2021
11220211230
11330 Dec 2021 00:38:54:840
11400:38:54:840
12030/12/2021 00:38
12138:54.8
1262021-12-30T00:38:54.840
1272021-12-30T00:38:54.840
130 7 رمضان 1443  8:17:54:640AM
-> should be  NVARCHAR
13126/05/1443  2:38:54:840AM

Post a Comment

0 Comments