简体   繁体   中英

How to get the First day and last day of the month from given month and year in sql

Hi I have a month number and year eg : month 2 and year 2014

how can i get the first day of that month like 2014-02-01 and last day of month 2014-02-28?

i have seen many posts on getting first and last date of month based on given date,but i need it based on given month and year

Thanks in advance

In SQL Server 2012 and later

DECLARE @year int = 2014
DECLARE @month int = 12

SELECT 
DATEFROMPARTS ( @year, @month, 1) AS MonthStart,
EOMONTH (DATEFROMPARTS ( @year, @month, 1) ) AS MonthEnd

Results

MonthStart MonthEnd
---------- ----------
2014-12-01 2014-12-31

(1 row(s) affected)

Further details DATEFROMPARTS: http://msdn.microsoft.com/en-gb/library/hh213228.aspx EOMONTH: http://msdn.microsoft.com/en-us/library/hh213020.aspx

In mysql :

  SELECT DATE_SUB(LAST_DAY(DATE_ADD(NOW(), INTERVAL 1 MONTH)), 
                    INTERVAL DAY(LAST_DAY(DATE_ADD(NOW(), INTERVAL 1 MONTH)))-1 DAY) AS firstOfNextMonth,
           LAST_DAY(DATE_ADD(NOW(), 
                    INTERVAL 1 MONTH)) AS lastOfNextMonth

in sql server :

select convert(varchar,dateadd(d,-(day(getdate()-1)),getdate()),106) 'Date'
union all
select  convert(varchar,dateadd(d,-day(getdate()),dateadd(m,1,getdate())),106)

SELECT DATEADD(mm, DATEDIFF(mm, 0, GETDATE()), 0)

SELECT DATEADD (dd, -1, DATEADD(mm, DATEDIFF(mm, 0, GETDATE()) + 1, 0))

Refernce : Get first and last day of month in SQL 2012 and SQL 2008

Not an answer to the OP, however may be helpful to others

Solution in postgres:

SELECT to_date((2012 || '-' || 9)::text, 'YYYY-MM') AS first_day, 
       (to_date((2012 || '-' || 9)::text, 'YYYY-MM') + interval  '1 month' - interval '1 day')::date AS last_day

On MS SQL Server 2008, the following seems to work:

DECLARE @Month INT = 10;
DECLARE @Year INT = 2016;
DECLARE @FirstDayOfMonth DATETIME = CAST(@Year AS varchar) + '-' + CAST(@Month AS VARCHAR) + '-1';
DECLARE @LastDayOfMonth DATETIME = DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @FirstDayOfMonth) + 1, 0));

SELECT @FirstDayOfMonth, @LastDayOfMonth; -- 2016-10-01, 2016-10-31

I had the same Problem a while back, so i created and saved the following codes. You can substitute the GetDate() with your own column name:

Select 
DATEADD(mm, DATEDIFF(mm, 0, Getdate())-1, 0)   as '1st day of last month',
dateadd(day,-(day(Getdate())),Getdate())  as 'last day of last month',
dateadd(mm,datediff(mm,0,Getdate()),0)as '1st day of this month',
dateadd(dd,-1,dateadd(mm,Datediff(mm,0,Getdate())+1,0)) as 'last day of this month',
dateadd(mm,datediff(mm,0,Getdate())+1,0) as '1st day of Next month',
Dateadd(dd,-1,dateadd(mm,datediff(mm,0,Getdate())+2,0))as 'Last day of Next month',

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM