Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get the first day and the last of previous month using sql

I am trying to get the first day of last month like 01/01/2013, also i want to get the last day of previous month like 01/31/2013. If we are in March then i want to do the same thing like 02/01/2013 and 02/28/2013 and so on.... thanks

like image 549
moe Avatar asked Feb 28 '13 20:02

moe


People also ask

How can I get first date and last date of previous month in SQL?

To get the previous month in SQL Server, subtract one month from today's date and then extract the month from the date. First, use CURRENT_TIMESTAMP to get today's date. Then, subtract 1 month from the current date using the DATEADD function: use MONTH as the date part with -1 as the parameter.

How get last day of previous month in SQL?

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 day of a month in SQL?

To find the first day, the date time is first converted to date only using TO_DATE function. Then, the date is changed to the first day of the month by using the DATE_FROM_PARTS function. This works by inputting 01' in the 'day' part of the function.

How do I get the start date and end date in SQL?

To use the dateadd function in SQL, we need to use the SELECT query followed by the DATEDIFF function and then return the output. The datePart should be provided only valid input (Check valid input table for datePart) and the startDate and the endDate should be provided with a date input in a proper format.


1 Answers

This should do it:

--First day of last month
SELECT DATEADD(m,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE()), 0))
--Last day of last month
SELECT DATEADD(d,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE()),0))
like image 138
Simon C Avatar answered Oct 14 '22 18:10

Simon C