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.
Next function returns non-negative Epoch time in VB.NET's DateTime format.
'''''' Converts Unix's epoch time to VB DateTime value ''' ''' Epoch time (seconds)'''VB Date '''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.
The function below converts DateTime type back to Unix's Epoch time.
'''''' Converts VB DateTime value to Unix's epoch time ''' ''' DateTime to convert'''Epoch time (seconds) '''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.
My version:
'''''' ''' Converts VB DateTime value to Unix's epoch time ''' ''' DateTime to convert'''Epoch time (seconds) '''Friend Shared Function DateTimeToEpoch(ByVal DateTimeValue As Date) As Integer Try Dim res As Integer Dim dataInizio As DateTime = New DateTime(1970, 1, 1, 0, 0, 0, 0) res = CInt(DateTimeValue.Subtract(dataInizio).TotalSeconds) Return res Catch ex As System.OverflowException Return -1 End Try End Function ''' ''' Converts Unix's epoch time to VB DateTime value ''' ''' Epoch time (seconds)'''VB Date '''Friend Shared Function EpochToDateTime(ByVal EpochValue As Integer) As Date Dim res As Date Dim dataInizio As DateTime = New DateTime(1970, 1, 1, 0, 0, 0, 0) If EpochValue >= 0 Then res = dataInizio.AddSeconds(EpochValue) Else res = dataInizio End If Return res End Function
via
via 2