Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Query to find the last day of the month

I need to find the last day of a month in the following format:

"2013-05-31 00:00:00:000" 

Anybody please help out.

like image 276
prabu R Avatar asked May 20 '13 09:05

prabu R


People also ask

How do you find the last day of the month in SQL?

If you would like to get the date containing the last day of the month of a given date, use the EOMONTH() function. This function takes one mandatory argument: a date (or date and time), which can be a date/datetime column or an expression that returns a date. (In our example, we use the PurchaseDate column.)

How do I select the last day in SQL?

MySQL LAST_DAY() Function The LAST_DAY() function extracts the last day of the month for a given date.

How get last day of previous month in SQL Server?

For the last day of the previous month: SELECT EOMONTH(DATEADD(MONTH,-1,GETDATE())); For the last day of the previous month formatted as needed: SELECT CONVERT(VARCHAR(10), EOMONTH(DATEADD(MONTH,-1,GETDATE())), 101);

How do I get the first and last day of the month in SQL?

The logic is very simple. The first part @DATE-DAY(@DATE) results to the Last day of a previous month and adding 1 to it will result on the first day of current month. The second part EOMONTH(@DATE) makes use of SYSTEM function EOMONTH which results to the last day of the given date.


1 Answers

Try this one -

CREATE FUNCTION [dbo].[udf_GetLastDayOfMonth]  (     @Date DATETIME ) RETURNS DATETIME AS BEGIN      RETURN DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @Date) + 1, 0))  END 

Query:

DECLARE @date DATETIME SELECT @date = '2013-05-31 15:04:10.027'  SELECT DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @date) + 1, 0)) 

Output:

----------------------- 2013-05-31 00:00:00.000 
like image 50
Devart Avatar answered Sep 23 '22 22:09

Devart