ASP 的 DateSerial 函数详解

2007年4月8日 by comehope    Tags: ASP  DateSerial  

下载本文的测试文件

DateSerial 函数根据给定的年、月、日的值,返回相应的日期型数据。
语法:DateSerial(year, month, day)
参数 year, month, day 均应为数值表达式。

例如,要得到年份为2007年,月份为4月份,日期为8日的一个日期型数据,可以这样写:

MyDate = DateSerial(2007,4,8)

再如,要得到去年的今天,则可以这样写:

MyDate = DateSerial(Year(Date())-1, Month(Date()), Day(Date()))

以下是几个 DateSerial 函数的应用:

获得给定日期所在月份的天数:

Function DaysInMonth (theDate)
 DaysInMonth = Day(DateSerial(Year(theDate), Month(theDate) + 1, 0))
End Function

获得给定日期距离年底的天数:

Function RemainDays (theDate)
 RemainDays = DateDiff("d",theDate,DateSerial((Year(Now()) + 1),1,1)) - 1
End Function

获得给定日期所在月份的最后一个工作日:

Function LastWorkDayInMonth (theDate)
 Dim D2
 D2 = DateSerial(Year(theDate), Month(theDate) + 1, 0)
 Do While Weekday(D2) = 1 Or Weekday(D2) = 7
   D2 = D2 - 1
 Loop
 LastWorkDayInMonth = D2
End Function

运行效果:

DateSerial 函数的二个 BUG :

1.DateSerial 函数帮助主题中说:“对于 year 参数,若取值范围是从 0 到 99,则被解释为 1900 到 1999 年”,这不正确。正确的说法应该是:year 参数介于 0 和 29 之间时,被解释为 2000 到 2029 年;介于 30 到 99 之间时,被解释为 1930 到 1999 年。

2.在当 year 参数为 99 时,对该年份加 1 的进位会产生错误。如下面的代码:

theDate = DateSerial(99 + 1, 1, 1)

得到的 theDate 值为 “100-1-1”,而不是“2000-1-1”

为避免出现以上二种错误,year 参数应该使用4位数字表示年份而不是只用2位。


发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。