First and Last Days of Year, Month, and Week in SQL Server

Hello to everyone,

In this article, I will try to give information about finding the first and last days of the year, month and week in SQL Server.

In SQL Server, in some cases you may want to find the first and last days of the year, month, and week.

You can easily do this using the code below.

DECLARE @tarih DATETIME = GETDATE();
SELECT 'Last Day of the Previous Month' Description,
       CONVERT(VARCHAR(10), DATEADD(dd, - (DAY(@tarih)), @tarih), 112) Date
UNION ALL
SELECT 'First Day of the Month',
       CONVERT(VARCHAR(10), DATEADD(dd, - (DAY(@tarih) - 1), @tarih), 112) AS Date_Value
UNION ALL
SELECT 'Today's date',
       CONVERT(VARCHAR(10), @tarih, 112) AS Date_Value
UNION ALL
SELECT 'Last Day of the Month',
       CONVERT(VARCHAR(10), DATEADD(dd, - (DAY(DATEADD(mm, 1, @tarih))), DATEADD(mm, 1, @tarih)), 112)
UNION ALL
SELECT 'First Day of Next Month',
       CONVERT(VARCHAR(10), DATEADD(dd, - (DAY(DATEADD(mm, 1, @tarih)) - 1), DATEADD(mm, 1, @tarih)), 112)
UNION ALL
SELECT 'The first day of the week',
       DATEADD(ww, DATEDIFF(ww, 0, GETDATE()), 0)
UNION ALL
SELECT 'First Day of Next Week',
       DATEADD(ww, DATEDIFF(ww, 0, GETDATE()) + 1, 0)
UNION ALL
SELECT 'First Day of the Year',
       DATEADD(yy, DATEDIFF(yy, 0, GETDATE()), 0)
UNION ALL
SELECT 'Last Day of the Year',
       DATEADD(dd, -1, DATEADD(yy, 0, DATEADD(yy, DATEDIFF(yy, 0, GETDATE()) + 1, 0)));

When you run the above code, you will see a result similar to the one below.

As you can see, we have seen the first and last days of the year, month and week.

Good luck to everyone in business and life.

84 Views

Yavuz Selim Kart

I try to explain what I know in software and database. I am still improving myself by doing research on many programming languages. Apart from these, I am also interested in Graphic Design and Wordpress. I also have knowledge about SEO and Social media management. In short, I am a determined person who likes to work hard.

You may also like...

Don`t copy text!