Time in Visual Basic .NET

Our program demonstrates extensive support for times and durations in Visual Basic .NET. Here are some examples:

Imports System

Module TimeExample
    Sub Main()
        ' We'll start by getting the current time.
        Dim now As Date = Date.Now
        Console.WriteLine(now)

        ' You can build a DateTime struct by providing the
        ' year, month, day, etc. Times are always associated
        ' with a specific time zone.
        Dim then As New DateTime(2009, 11, 17, 20, 34, 58, 651, DateTimeKind.Utc)
        Console.WriteLine(then)

        ' You can extract the various components of the time
        ' value as expected.
        Console.WriteLine(then.Year)
        Console.WriteLine(then.Month)
        Console.WriteLine(then.Day)
        Console.WriteLine(then.Hour)
        Console.WriteLine(then.Minute)
        Console.WriteLine(then.Second)
        Console.WriteLine(then.Millisecond)
        Console.WriteLine(then.Kind)

        ' The day of the week is also available.
        Console.WriteLine(then.DayOfWeek)

        ' These methods compare two times, testing if the
        ' first occurs before, after, or at the same time
        ' as the second, respectively.
        Console.WriteLine(then < now)
        Console.WriteLine(then > now)
        Console.WriteLine(then = now)

        ' The Subtract method returns a TimeSpan representing
        ' the interval between two times.
        Dim diff As TimeSpan = now.Subtract(then)
        Console.WriteLine(diff)

        ' We can compute the length of the duration in
        ' various units.
        Console.WriteLine(diff.TotalHours)
        Console.WriteLine(diff.TotalMinutes)
        Console.WriteLine(diff.TotalSeconds)
        Console.WriteLine(diff.TotalMilliseconds)

        ' You can use Add to advance a time by a given
        ' duration, or with a negative value to move backwards by a
        ' duration.
        Console.WriteLine(then.Add(diff))
        Console.WriteLine(then.Add(-diff))
    End Sub
End Module

To run the program, save it as TimeExample.vb and use the VB.NET compiler:

$ vbc TimeExample.vb
$ mono TimeExample.exe
5/30/2023 10:15:30 AM
11/17/2009 8:34:58 PM
2009
11
17
20
34
58
651
Utc
Tuesday
True
False
False
124452:40:32.3456789
124452.6756515491
7467160.539309295
448029632.3585577
448029632358.5577
5/30/2023 10:15:30 AM
5/5/1996 6:54:25 PM

This example demonstrates working with dates and times in Visual Basic .NET. It covers creating date/time objects, extracting components, comparing times, calculating durations, and performing time arithmetic. The DateTime and TimeSpan structures in .NET provide similar functionality to Go’s time package.

Next, we’ll look at the related idea of time relative to the Unix epoch.