Recommended Books

VB.NET Datetime



This article covers Datetime in Visual Basic (VB.NET).

A large portion of software and applications written utilize Dates in one way or the other. Whether it’s a time based expiry, a Calendar or time management system, knowing how to create and return Dates if vital.

The Datetime class in VB.NET allows us manipulate Dates as well as Time in a variety of different ways. It also comes with several parsing functions which parse through strings to create Datetime objects. Let’s begin.


VB.NET DateTime Functions and Properties

The DateTime Class has dozens of different properties and functions, so covering them all in depth is a bit difficult. We’ll cover the most useful and common ones here, and the rest will be mentioned in a list at the end of this article.

Properties

The Today property returns the Date for the current day or “Today”. Note however, that it does not return the current time, instead returning the default time of 12:00:00 AM.

Module Module1
    Sub Main()

        Dim time As DateTime = DateTime.Today
        Console.WriteLine(time)

    End Sub
End Module
21/05/2020 12:00:00 AM

The Now property returns both the current time and the current date. Compare this to the Today property which only returns the current date.

Module Module1
    Sub Main()

        Dim time As DateTime = DateTime.Now
        Console.WriteLine(time)

    End Sub
End Module
21/05/2020 5:58:33 PM

The DayOfWeek property returns an integer which represents which day of the week it is. The integer value will range from 1 to 7, where 1 represents Monday.

Module Module1
    Sub Main()

        Dim time As DayOfWeek
        time = DateTime.Today.DayOfWeek
        Console.WriteLine(time)

    End Sub
End Module
4

This code was run on a Thursday, hence 4 was returned. There is also the DayofYear property which returns an integer value ranging from 1 to 366.

The Datetime object consists of many smaller components such as Hour and Year. These properties are used to return certain parts of the Datetime object.

Module Module1
    Sub Main()
        Dim time As DateTime = DateTime.Now
        Console.WriteLine(time)

        'Full Date
        Console.WriteLine(time.Date)

        'Year portion of the Date
        Console.WriteLine(time.Year)

        'Month portion of the Date
        Console.WriteLine(time.Month)

        'Day portion of the Date
        Console.WriteLine(time.Day)

        Console.WriteLine()

        'Full Time
        Console.WriteLine(time.TimeOfDay)

        'Hour portion of the Time
        Console.WriteLine(time.Hour)

        'Minute portion of the Time
        Console.WriteLine(time.Minute)

        'Second portion of the Time
        Console.WriteLine(time.Second)

        'Millisecond portion of the Time
        Console.WriteLine(time.Millisecond)

        Console.Read()
    End Sub
End Module
22/05/2020 5:27:34 PM
22/05/2020 12:00:00 AM
2020
5
22

17:27:34.3020342
17
27
34
302

Functions

The AddDays(n) function takes a integer as input, and adds this integer to the Datetime object it is called upon. You can use this as a way to return the Dates for the tomorrow and yesterday as shown below.

Module Module1
    Sub Main()

        Dim time As DateTime = DateTime.Today

        Console.WriteLine(time)
        Console.WriteLine(time.AddDays(1))
        Console.WriteLine(time.AddDays(-1))

    End Sub
End Module
21/05/2020 12:00:00 AM
22/05/2020 12:00:00 AM
20/05/2020 12:00:00 AM

The AddDays function works on all Datetime objects, not just Datetime.Today. Furthermore, there are another dozen types of functions similar to this such as AddHours, AddDays, AddMinutes with the exact same implementation.

The DaysInMonth() Function takes two parameters, a Year and a Month. Both must be integers with the month ranging from 1 – 12. This function will accordingly return the number of days supposed to be in that month.

Module Module1
    Sub Main()

        Dim time As Integer
        time = DateTime.DaysInMonth(2012, 2)
        Console.WriteLine(time)

    End Sub
End Module
29

This function accounts for Leap years as well, hence the February in 2012 has 29 days.

The Compare function compares two datetime objects and returns an integer that indicates whether the first datetime object is earlier than the second.

Module Module1
    Sub Main()

        Dim date1 As DateTime = New DateTime(2020, 5, 21)
        Dim date2 As DateTime = New DateTime(2020, 5, 21)
        Dim date3 As DateTime = New DateTime(2019, 3, 15)
        Dim date4 As DateTime = New DateTime(2021, 4, 4)

        Console.WriteLine(DateTime.Compare(date2, date1))
        Console.WriteLine(DateTime.Compare(date2, date3))
        Console.WriteLine(DateTime.Compare(date2, date4))


        Console.Read()
    End Sub
End Module
0
1
-1

If 1 is returned, the first datetime object is earlier than the second, otherwise -1 is returned. In the event that both dates are equal, 0 is returned.


Time Zone Functions and properties

This is a small mini section on dealing with different time zones. The core concept here is that there will be different Dates and Times for different locations around the globe, hence different Time Zones. If you have a software that depends heavily on Dates, if you don’t account for different Time zones, there will be trouble.

First step is to create the TimeZone object. The StandardName is the name of the current Time zone. The DaylightName represents the name for the DaylightSavings. That’s a topic for another day though.

Finally we use the ToLocalTime and ToUniversalTime functions to convert the current time into the appropriate Time zone. This conversion is necessary as TimeZone and DateTime are two separate Classes.

Module Module1
    Sub Main()

        Dim time As TimeZone = TimeZone.CurrentTimeZone
        Console.WriteLine(time.StandardName)
        Console.WriteLine(time.DaylightName)

        Console.WriteLine(time.ToLocalTime(DateTime.Now))
        Console.WriteLine(time.ToUniversalTime(DateTime.Now))

    End Sub
End Module
Pakistan Standard Time
Pakistan Daylight Time
21/05/2020 8:38:23 PM
21/05/2020 3:38:23 PM

Shown above is the output I receive when I run this function. The output will change depending on the time zone you are in.

There is more to this class than shown above, this was just a brief overlook. Follow this link to learn more about the different Time Zones in VB.NET.


Parsing Strings with Date and Time

The Parse function allows us to convert strings into Datetime objects. The best part about this function is how flexible it is. As you’ll see in the examples below, this function can accept Strings in all kinds of different String formats.

Module Module1
    Sub Main()

        ' Slash format
        Dim time As DateTime = DateTime.Parse("2/1/2007")
        Console.WriteLine(time)

        ' Comma format
        time = DateTime.Parse("2,7,2002")
        Console.WriteLine(time)

        ' HTTP headers
        time = DateTime.Parse("Tue, 26 Feb 2019 06:31:21 GMT")
        Console.WriteLine(time)

        ' From Windows Operating System
        time = DateTime.Parse("4:40:19 PM")
        Console.WriteLine(time)

        time = DateTime.Parse("2/8/2020 2:35 PM")
        Console.WriteLine(time)

        ' From ISO Standard 8601 for Dates
        time = DateTime.Parse("2001-04-14")
        Console.WriteLine(time)

        ' From other reputable sites
        time = DateTime.Parse("2006/02/23 18:31:38")
        Console.WriteLine(time)

        time = DateTime.Parse("Tuesday, January 11, 2011")
        Console.WriteLine(time)

        time = DateTime.Parse("April 4, 2001")
        Console.WriteLine(time)

        Console.Read()
    End Sub
End Module
02/01/2007 12:00:00 AM
02/07/2002 12:00:00 AM
26/02/2019 11:31:21 AM
21/05/2020 4:40:19 PM
02/08/2020 2:35:00 PM
14/04/2001 12:00:00 AM
23/02/2006 6:31:38 PM
11/01/2011 12:00:00 AM
04/04/2001 12:00:00 AM

The Datetime library returns a “Datetime” object, which includes both the Date and the Time. If the Time was not specified, it is given the default value of 12:00:00 AM. If the Date is not specified, by default the current date is returned. In this case, I ran this code on May 21st 2020 and the 4th Output reflects this.


Creating a DateTime object

All of the above functions create and return DateTime objects, but what if we wish to create one of our choosing? Since DateTime is a class, we can create an object by passing the right input arguments to it.

One of the benefits of having a DateTime object instead of a String or something is the ability to compare DateTime objects to each other. You can’t compare two Strings with dates to find which one is the smaller one. In the example below, we’ll use several comparison operators on different dates.

The DateTime Class takes three arguments, Year, Month and Day in this order.

Module Module1
    Sub Main()
       
        Dim date1 As DateTime = New DateTime(2020, 5, 21)
        Dim date2 As DateTime = New DateTime(2020, 5, 21)
        Dim date3 As DateTime = New DateTime(2019, 3, 15)
        Dim date4 As DateTime = New DateTime(2021, 4, 4)

        If date1 = date2 Then
            Console.WriteLine("Equal dates")
        End If

        If date3 < date2 Then
            Console.WriteLine("Date3 is older than Date2")
        End If

        If date4 > date2 Then
            Console.WriteLine("Date4 is newer than Date2")
        End If

    End Sub
End Module

Bonus Material: VB.NET has many different Classes that deal with Dates and Time. You’ve already dealt with two such classes, DateTime and TimeZone. If you’re interested in learning more, you should look up the Date and Timer Classes.


This marks the end of the VB.NET Datetime article. Any suggestions or contributions for CodersLegacy are more than welcome. Questions can be asked in the comments section below.

Leave a Reply

Your email address will not be published. Required fields are marked *