support@codebucket.net

How to get the first date and last date of the month from GETDATE() in mssql

How to get the first date and last date of the month from GETDATE() in mssql

K. M. Shawkat Zamil | October 12, 2022

Hello Developers,

In this demonstration, you will find out how to get the first date and last date of the current month from GETDATE() MSSQL. In many cases, we need the right code to find the first date and last date from GETDATE(). I have found the specific thing you need. Here is the code. Just run the below code in your mssql server editor.

 

SELECT CAST(CAST(YEAR(GETDATE()) AS VARCHAR(4)) +'-'+CAST(MONTH(GETDATE()) AS VARCHAR(2))+'-01' AS DATETIME) as FirstDateOfCurrentMonth

SELECT DATEADD(MONTH, 1, CAST(CAST(YEAR(GETDATE()) AS VARCHAR(4)) +'-'+CAST(MONTH(GETDATE()) AS VARCHAR(2))+'-01' AS DATETIME)) - 1 as LastDateOfCurrentMonth

SELECT CAST(CAST(YEAR(DATEADD(month, -1, GETDATE())) AS VARCHAR(4)) +'-'+CAST(MONTH(DATEADD(month, -1, GETDATE())) AS VARCHAR(2))+'-01' AS DATETIME) as FirstDateOfPreviousMonth

SELECT DATEADD(MONTH, 1, CAST(CAST(YEAR(DATEADD(month, -1, GETDATE())) AS VARCHAR(4)) +'-'+CAST(MONTH(DATEADD(month, -1, GETDATE())) AS VARCHAR(2))+'-01' AS DATETIME)) - 1 as LastDateOfPreviousMonth

 

I hope this might help in your development journey.

 

Read More: How to get column values in one comma separated value

 

K. M. Shawkat Zamil

K. M. Shawkat Zamil

Senior Software Engineer

I am a Senior Software Engineer in a reputed company in Bangladesh. I am a big fan of Laravel, PHP Programming, MSSQL Server, MySql, JavaScript, and lots more. I love to help people who are especially eager to learn. I believe in patience and motivation.