Question : Convert datetime to character string


How can I convert a sql server datetime to a character string. I want to display the getdate() function in the format "MM/DD/YYYY HH:MI:SS AM/PM".. I'll appreciate any examples..

Answer : Convert datetime to character string

Style Code   Style                                 Format              Example
101                  USA date with century.   mm/dd/yyyy      09/08/2007
8 or 108          24 hour time.                 HH:mm:ss      21:00:00

The Transact-SQL (T-SQL) Convert command can be used to convert data between different types. When converting a DATETIME value to a VarChar string value a style code may be applied. The closest you can get to your format is by concatenating the above 2 style codes i.e.

SELECT convert(VARCHAR, getdate(),101) + ' ' + convert(VARCHAR, getdate(),108)

Now you write,
IF HH >= 00 and HH <= 12, then AM and
IF HH >=12 and HH <= 23, then PM
Random Solutions  
 
programming4us programming4us