getting date in a very specific format

  • I need to get the date in a very specific format, YYYYMMDD, where YYYY = year, MM = month and DD = day.

    I am doing this at present with this line:

    select

    @d = convert(varchar(4),datepart(year,getdate())) + convert(varchar(2),datepart(mm,getdate())) + convert(varchar(2),datepart(dd,getdate()))

     

    This works, but i if the month or day is a single digit, there is no 0 before it. eg

    my code returns, for today, 2007127, and i need it to return 20070127. I need it to put a 0 before the day also, if it is less than 10. any ideas how to simply do this withough a bunch of if statements?

  • SELECT CONVERT(CHAR(8), GETDATE(), 112)

    --------

    20070125

    The format you want is also known as the ISO format (look up 'convert' in BOL and you'll see the different styles you can fomat dates in there)

    I want to shake your hand on the choice of format, since this is the one and only 100% safe format to handle dates as text, without any risk of it being misunderstood or distorted due to datesettings or language.

    /Kenneth

  • perfect!!! thanks a mil. you just made my life a little bit easier!

Viewing 3 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply