Thursday, March 29, 2012

Getting the number of hours in a month

Hi,
I'd like a function that returns the number of hours in a specific month (or the number of days which I could then multiply by 24). The function would have to consider leap years for February.
Any ideas?
Thanks,
Skip.Hi Skip, this calculates the number of hours in the month containing the date 20040101.

select 24 * datepart("d", dateadd("d", -1, dateadd("m", 1, '20040101')))

It goes 1 month forward, then 1 day back to get the last day of the month. The 24 * converts days to hours.

This does not take into account daylight savings :-(|||declare @.month datetime
set @.month = getdate()

select datediff(hour, convert(char(7), @.month, 120)+'-01', dateadd(month, 1, convert(char(7), @.month, 120)+'-01'))|||At least for the United States, you could use:CREATE FUNCTION fHoursInMonth(@.pd1 DATETIME) RETURNS INT AS
BEGIN
DECLARE
@.dWork DATETIME

SET @.dWork = Convert(CHAR(8), @.pd1, 121) + '01'
RETURN 24 * DateDiff(day, @.dWork, DateAdd(month, 1, @.dWork))
+ CASE Month(@.dWork)
WHEN 4 THEN -1 -- Lose an hour to "Spring forward"
WHEN 10 THEN 1 -- Gain an hour from "Fall back"
ELSE 0
END
END-PatP|||I would think that datediff(hour...) would account for leap years and daylight savings.|||Not according to:SELECT a.d, dbo.fHoursInMonth(a.d), DateDiff(hour, a.d, DateAdd(month, 1, a.d))
FROM (
SELECT '2004-01-15' AS d
UNION SELECT '2004-02-15'
UNION SELECT '2004-03-15'
UNION SELECT '2004-04-15'
UNION SELECT '2004-05-15'
UNION SELECT '2004-06-15'
UNION SELECT '2004-07-15'
UNION SELECT '2004-08-15'
UNION SELECT '2004-09-15'
UNION SELECT '2004-10-15'
UNION SELECT '2004-11-15'
UNION SELECT '2004-12-15') AS aThe biggest problem is that the observance of Daylight Savings time, the dates of the changes, and even the amount of change (not everyone uses one hour) are location dependant.

-PatP|||Humph! :( :(

No comments:

Post a Comment