如何获得月份和年份的天数 [英] How to get number of days from month and year

查看:204
本文介绍了如何获得月份和年份的天数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获取用户指定的月份中的天数.我正在使用它,除了2月和leap年,它在大多数月份都有效.它显示28天而不是29天.您能解决这个问题吗?

I want to get the number of days in the month which the user specifies. I am using this it works for most months except for Feb and leap year. It shows 28 days and not 29. Can you solve this?

begin
declare @year int
declare @month int
select @year = 2012
select @month = DATEPART(mm,CAST('August'+ ' 2012' AS DATETIME))
select  datediff(day, 
        dateadd(day, 0, dateadd(month, ((@year - 2012) * 12) + @month - 1, 0)),
        dateadd(day, 0, dateadd(month, ((@year - 2012) * 12) + @month, 0))) as number_of_days

end

或者,如果不能,您可以告诉我另一种方法来执行此操作.它应该使用@year@month并且查找日期的代码可以是任意的!

Or If not can you tell me another approach to do this. It should use @year and @month and the code to find the days can be any!

推荐答案

如果您需要从年份和月份开始(假设两者都是整数),则可以这样创建一个函数:

If you need to do this from year and month (assuming both are integers) you could create a function as so:

CREATE FUNCTION dbo.DaysInMonth (@year INT, @Month INT)
RETURNS INT 
AS
BEGIN
    -- FIRST CONVERT THE YEAR AND MONTH TO A DATE BY CASTING TO CHAR
    -- THEN CONCATENATING TO CREATE A STRING IN THE FORMAT yyyyMMdd
    -- THIS DATEFORMAT IS CULTURE INSENSITIVE SO WILL WORK NO MATTER
    -- WHAT YOUR REGIONAL SETTINGS ARE

    DECLARE @Date DATE = CAST(
                            CAST(@Year AS CHAR(4)) 
                            + RIGHT('0' + CAST(@Month AS VARCHAR(2)), 2)
                            + '01' AS DATE);

    -- USE ESTABLISHED METHODS OF GETTING 1ST OF THE MONTH AND FIRST OF 
    -- THE NEXT MONTH AND CALCULATE THE DIFFERENCE
    RETURN DATEDIFF(DAY, 
            DATEADD(MONTH, DATEDIFF(MONTH, 0, @Date), 0),
            DATEADD(MONTH, DATEDIFF(MONTH, 0, @Date) + 1, 0));
END
GO
-- TEST FUNCTION
SELECT  DaysInMonth = dbo.DaysInMonth(2012, 2);

关于SQL提琴的示例

Example on SQL Fiddle

这篇关于如何获得月份和年份的天数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆