Epoch in Visual Basic .NET
Our first program demonstrates how to get the number of seconds, milliseconds, or nanoseconds since the Unix epoch. Here’s how to do it in Visual Basic .NET.
Imports System
Module Epoch
Sub Main()
' Use DateTime.UtcNow to get the current UTC time
Dim now As DateTime = DateTime.UtcNow
Console.WriteLine(now)
' Convert to Unix timestamp (seconds since epoch)
Dim unixTimestamp As Long = CLng(now.Subtract(New DateTime(1970, 1, 1)).TotalSeconds)
Console.WriteLine(unixTimestamp)
' Convert to milliseconds since epoch
Dim unixTimestampMillis As Long = CLng(now.Subtract(New DateTime(1970, 1, 1)).TotalMilliseconds)
Console.WriteLine(unixTimestampMillis)
' Convert to nanoseconds since epoch (approximation, as .NET doesn't have nanosecond precision)
Dim unixTimestampNanos As Long = CLng(now.Subtract(New DateTime(1970, 1, 1)).TotalMilliseconds) * 1000000
Console.WriteLine(unixTimestampNanos)
' Convert Unix timestamp back to DateTime
Dim dateTimeFromUnix As DateTime = New DateTime(1970, 1, 1).AddSeconds(unixTimestamp)
Console.WriteLine(dateTimeFromUnix)
' Convert nanoseconds back to DateTime (approximation)
Dim dateTimeFromNanos As DateTime = New DateTime(1970, 1, 1).AddMilliseconds(unixTimestampNanos / 1000000)
Console.WriteLine(dateTimeFromNanos)
End Sub
End Module
In this example, we use DateTime.UtcNow
to get the current UTC time. We then demonstrate how to convert this to seconds, milliseconds, and nanoseconds since the Unix epoch (January 1, 1970).
To run the program, save it as Epoch.vb
and use the VB.NET compiler:
$ vbc Epoch.vb
$ mono Epoch.exe
5/5/2023 12:34:56 PM
1683290096
1683290096789
1683290096789000000
5/5/2023 12:34:56 PM
5/5/2023 12:34:56 PM
Note that Visual Basic .NET doesn’t have built-in methods for Unix time like UnixMilli
or UnixNano
. Instead, we calculate these values by subtracting the Unix epoch from the current time and converting the result to the appropriate unit.
Also, be aware that the nanosecond precision in this example is an approximation, as .NET’s DateTime type only has precision up to 100 nanoseconds (ticks).
Next, we’ll look at another time-related task: time parsing and formatting in Visual Basic .NET.