Unix and Unix-like systems, like Linuxes, use Unix Epoch time in system time and time handling libraries. Sometimes you may need to handle these Epoch times in VB.NET or simply convert Epoch times to VB.NET's DateTime type.
Unix Epoch is the number of seconds from midnight January 1, 1970 and value is commonly stored in signed 32-bit integer value. This, however, causes so called year 2038 problem because in January 19, 2038 value reaches 2 147 483 647 and after that "wraps around". But let's not worry about that.
Convert Unix Epoch time to VB.NET DateTime value
Next function returns non-negative Epoch time in VB.NET's DateTime format.
''' <summary> ''' Converts Unix's epoch time to VB DateTime value ''' </summary> ''' <param name="EpochValue">Epoch time (seconds)</param> ''' <returns>VB Date</returns> ''' <remarks></remarks> Public Function EpochToDateTime(ByVal EpochValue As Integer) As Date ' If EpochValue >= 0 Then Return CDate("1.1.1970 00:00:00").AddSeconds(EpochValue) Else Return CDate("1.1.1970 00:00:00") End If End Function
With negative parameters, the value returned is the same as with Epoch time 0.
Convert VB.NET DateTime value to Unix's Epoch time
The function below converts DateTime type back to Unix's Epoch time.
''' <summary> ''' Converts VB DateTime value to Unix's epoch time ''' </summary> ''' <param name="DateTimeValue">DateTime to convert</param> ''' <returns>Epoch time (seconds)</returns> ''' <remarks></remarks> Public Function DateTimeToEpoch(ByVal DateTimeValue As Date) As Integer ' Try Return CInt(DateTimeValue.Subtract(CDate("1.1.1970 00:00:00")).TotalSeconds) Catch ex As System.OverflowException Return -1 End Try End Function
Since .NET's DateTime can store dates far beyond year 2038, function traps OverFlow exception. When you use this function, you have to check that the returned value is positive integer and consequently valid Epoch value.
1 comment:
Wonderful! Thank you!!
Post a Comment