Date/Time Manipulation in .Net

Discussion in 'Visual Basic [VB]' started by pradeep, May 6, 2007.

  1. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,645
    Likes Received:
    87
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    http://blog.pradeep.net.in
    While it has become common practice for developers to manipulate VB.NET date/time values manually, it's never a good idea because the result is rarely a correct date/time value. Whenever you try to use your own calculation routines for adding and subtracting date/time values, you risk generating a bug since it's hard to check the code for all possible outcomes, whereas utilizing appropriate .NET objects and methods is sure to provide correct results.

    As you can see in Snippet A, the Date object provides for simple manipulation, which allows you to add and subtract date/time values in VB.NET. In the example, We define the Date variable dtNow and set it to the current date/time value. We utilize these Date object methods to manipulate the date: AddYears, AddMonths, AddDays, AddHours, AddMinutes, AddSeconds, and AddMilliseconds. For each method, we specify the number of years or months or hours to add. Subtraction is done by passing a negative value to the method. Notice that these methods will never result in an impossible date; manual manipulation cannot guarantee such results.

    Snippet A
    Code:
      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
      
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice