您好我有一个月号和年份,例如:2014年第2年和第2年
我怎样才能获得当月的第一天,如2014-02-01和2014-02-28的最后一天?
根据给定的日期,我看过许多关于获得第一个月和最后一个月的帖子,但我需要基于给定的月份和年份
提前致谢
答案 0 :(得分:2)
在SQL Server 2012及更高版本中
DECLARE @year int = 2014
DECLARE @month int = 12
SELECT
DATEFROMPARTS ( @year, @month, 1) AS MonthStart,
EOMONTH (DATEFROMPARTS ( @year, @month, 1) ) AS MonthEnd
结果
MonthStart MonthEnd
---------- ----------
2014-12-01 2014-12-31
(1 row(s) affected)
更多细节 日期:http://msdn.microsoft.com/en-gb/library/hh213228.aspx EOMONTH:http://msdn.microsoft.com/en-us/library/hh213020.aspx
答案 1 :(得分:0)
在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
在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)
答案 2 :(得分:0)
当月的第一天:
SELECT DATEADD(mm, DATEDIFF(mm, 0, GETDATE()), 0)
要获取当月的最后一天:
SELECT DATEADD (dd, -1, DATEADD(mm, DATEDIFF(mm, 0, GETDATE()) + 1, 0))
答案 3 :(得分:0)
不是OP的答案,但可能对其他人有帮助
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
答案 4 :(得分:0)
在MS SQL Server 2008上,以下似乎有效:
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
答案 5 :(得分:0)
前一段时间我遇到了同样的问题,所以我创建并保存了以下代码。您可以用自己的列名替换GetDate()
:
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',