計算特定月份的天數
出自ProgWiki
目錄 |
用途
- 以年份與月份的數值,計算出該月的總天數。
(閏年規則,四年一閏,百年不閏,四百年再閏)
MS-SQL預存函數版本
SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE FUNCTION [dbo].[GetDaysCount] ( @theYear AS INT, @theMonth AS INT; ) RETURNS INT AS BEGIN DECLARE @theDays AS INT; IF (@theMonth=2) BEGIN IF (((@theYear % 4 = 0) and (@theYear % 100 <> 0)) or (@theYear % 400 = 0)) SET @theDays = 29 ELSE SET @theDays = 28 END ELSE BEGIN SELECT @theDays = CASE WHEN (@theMonth in (1,3,5,7,8,10,12))THEN 31 ELSE 30 END; END RETURN @theDays END
C#版本
public class DateHelper { public static int GetDaysCount(int theYear, int theMonth) { int theDays; //計算該月天數 switch (theMonth) { //31 day case 1: case 3: case 5: case 7: case 8: case 10: case 12: theDays = 31; break; //28 or 29 day case 2: theDays = 28; if (((theYear % 4 == 0) && (theYear % 100 != 0)) || (theYear % 400 == 0)) theDays = 29; break; //30 day default: theDays = 30; break; } return theDays; } }
VB6版本
Public Function GetDaysCount(theYear as Integer, theMonth as Integer) as Integer '計算該月天數 Select Case theMonth '31 day case 1, 3, 5, 7, 8, 10, 12 GetDaysCount = 31 '28 or 29 day case 2 if (((theYear % 4 = 0) and (theYear mod 100 <> 0)) or (theYear mod 400 = 0)) Then GetDaysCount = 29 Else GetDaysCount = 28 End If '30 day Case Else GetDaysCount = 30 End Select End Function
VB.NET版本
Public Class DateHelper Public Shared Function GetDaysCount(ByVal theYear As Integer, ByVal theMonth As Integer) As Integer Dim theDays As Integer '計算該月天數 Select Case theMonth '31 day Case 1, 3, 5, 7, 8, 10, 12 theDays = 31 Exit Select '28 or 29 day Case 2 theDays = 28 If ((theYear Mod 4 = 0) AndAlso (theYear Mod 100 <> 0)) OrElse (theYear Mod 400 = 0) Then theDays = 29 End If Exit Select '30 day Case Else theDays = 30 Exit Select End Select Return theDays End Function End Class
JavaScript版本
function GetDaysCount(theYear, theMonth) { var theDaysArray1 = new Array(31,28,31,30,31,30,31,31,30,31,30,31); var theDaysArray2 = new Array(31,29,31,30,31,30,31,31,30,31,30,31); if (((theYear%4 == 0) && (theYear%100 != 0)) || (theYear%400 == 0)) { return theDaysArray2[theMonth]; } else { return theDaysArray1[theMonth]; } }
其他
- 小朱版本(MS-SQL與C#)(利用時間差的算法)