虽然手工操纵VB.NET中日期/时间类型的值已经成为开发人员的公共习惯,但是这并不是一个好主意,因为结果很少是正确的日期/时间值。 无论什么时候,当你试图用自己的计算路径进行日期/时间值的加减运算时,都有可能产生一个漏洞,因为我们很难检查代码的所有可能输出结果。然而使用恰当的.NET对象与方法是可以确保得到正确的结果的。 正如在列表A中所看到的,我们可以使用Date对象提供的简单操作来进行VB.NET中日期/时间值的加减运算。在本例中,我们定义了Date对象的实例dtNowand,并设定值为当前日期/时间。 使用下面Date对象的方法来处理日期:AddYears, AddMonths, AddDays, AddHours, AddMinutes, AddSeconds, and AddMilliseconds。 对每个方法,我们分别指定进行加法运算的年、月或日的值。减法运算可以通过传递给方法一个负值来来实现。注意这些方法决不会返回一个非法的日期,而手工操作不能保证这样的结果。 Private Sub AddDateTime()
Dim dtNow As Date = Now() MsgBox(dtNow)
dtNow = dtNow.AddYears(20) MsgBox(dtNow) the Date object provides for simple manipulation that allows you to add and subtract date/time values in VB.NET.
dtNow = dtNow.AddMonths(10) MsgBox(dtNow)
dtNow = dtNow.AddDays(3) MsgBox(dtNow)
dtNow = dtNow.AddHours(5) MsgBox(dtNow)
dtNow = dtNow.AddMinutes(2) MsgBox(dtNow)
dtNow = dtNow.AddSeconds(6) MsgBox(dtNow)
dtNow = dtNow.AddMilliseconds(4) MsgBox(dtNow)
dtNow = dtNow.AddYears(-2) MsgBox(dtNow)
End Sub 转http://dotnet.chinaitlab.com/
Dim dtNow As Date = Now() MsgBox(dtNow)
dtNow = dtNow.AddYears(20) MsgBox(dtNow) the Date object provides for simple manipulation that allows you to add and subtract date/time values in VB.NET.
dtNow = dtNow.AddMonths(10) MsgBox(dtNow)
dtNow = dtNow.AddDays(3) MsgBox(dtNow)
dtNow = dtNow.AddHours(5) MsgBox(dtNow)
dtNow = dtNow.AddMinutes(2) MsgBox(dtNow)
dtNow = dtNow.AddSeconds(6) MsgBox(dtNow)
dtNow = dtNow.AddMilliseconds(4) MsgBox(dtNow)
dtNow = dtNow.AddYears(-2) MsgBox(dtNow)
End Sub 转http://dotnet.chinaitlab.com/
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货