Thursday, April 28, 2011

Conversion format from time to default datetime

hi guys, i have time as 1:00PM.I have to convert to format '1/1/1900 01:00:00 PM'.Can anybody help?

From stackoverflow
  • STEP 1: Let's get the date and save it into @Date variable.

    DECLARE @Date DATETIME;
    SELECT @Date = CONVERT(DATETIME, '1:00PM' , 100);
    

    Now @Date = 1900-01-01 13:00:00.000

    STEP 2: Let's convert it into custom format

    SELECT CONVERT(VARCHAR, @Date, 101) + ' '
           + REPLACE(LTRIM(SUBSTRING(CONVERT(VARCHAR, @Date, 131), 12, 14)),
           ':000', ' ');
    

    This returns '1/1/1990 1:00:00 PM'

    : i need date format as 1/1/1900 1:00:00 PM.Now the result iam getting as 1900-01-01 13:00:00.000
    : Can u give appropriate code?
    Koistya Navin : @ramyatk06, here it is.
  • select convert(datetime , "1/1/1900 " + "1:00 PM" , 101)
    
    : Got one error as "Conversion failed when converting datetime from character string."
    Learning : the space in '1/1/1900 ' is significant. I hope you did not overlook it!
  • See "CAST and CONVERT" in sql server books online

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

    you probably want 131 but return it as a varchar

    so

    SELECT CONVERT(VARCHAR(20),GETDATE(),131)
    

0 comments:

Post a Comment