Converting getdate() to yyyymmdd & getting the date two years back

62,311

Solution 1

You can also use FORMAT:

 select FORMAT(getdate(), 'yyyyMMdd')

Solution 2

Try CONVERT(char(8), GETDATE(), 112)

Also check https://technet.microsoft.com/en-us/library/ms187928(v=sql.105).aspx

Share:
62,311
Brandon
Author by

Brandon

Updated on January 22, 2020

Comments

  • Brandon
    Brandon over 4 years

    I have found a couple of different methods to convert it. However, I still get the yyyy-mm-dd format or yyyy-mm-dd hh:mm:ss. I am currently using SQL Server 2014.

    SELECT dateadd(day, convert(int, getdate()), 112)
    SELECT DATEADD(YEAR, -2, convert(DATE, GETDATE(), 112))
    

    I am doing a date range of 2 years. Thus I need the codes to the find the date two years back.

  • Brandon
    Brandon almost 8 years
    why do I get "20160025"? seems rather weird.
  • vercelli
    vercelli almost 8 years
    Try now, with yyyyMMdd instead of yyyymmdd
  • Brandon
    Brandon almost 8 years
    Thanks a lot man. This is the code I am looking for. If it isn't too much, how do I get the date for 2 years back?
  • nilsman
    nilsman almost 8 years
    dateadd(year, -2, getdate());
  • Brandon
    Brandon almost 8 years
    yup it works now. Thanks for the codes man. If it isn't too much, could you help me with the codes to get the date two years back?
  • vercelli
    vercelli almost 8 years
    @Brandon SELECT FORMAT(DATEADD(YEAR, -2, getdate()), 'yyyyMMdd')
  • Brandon
    Brandon almost 8 years
    Would it be possible to take out the time? Also the date format is not what i requested.
  • Juan Velez
    Juan Velez almost 4 years
    @Brandon Yes it is possible.