0

I have a sensor which outputs in universal time (number of seconds since midnight January 1st (Universal Time), 1904).

In excel I can use the following equation (UTtime / 86400) + 1462, then format the cell in normal date format.

When I'm reading the value into vb net app, do you know how I can convert this value into a DateTime variable

Chris
  • 317
  • 3
  • 7
  • 12
  • 1
    VBScript or VB.NET? Tag says one thing, the question says another; the refernce to excel implies vba. The number of seconds since 1904 is not universal time, it is some sort of oddball epoch or proprietary serial time. – Ňɏssa Pøngjǣrdenlarp Sep 01 '17 at 15:12
  • Possible duplicate of [Convert UTC/GMT time to local time](https://stackoverflow.com/questions/179940/convert-utc-gmt-time-to-local-time) – TyCobb Sep 01 '17 at 15:12
  • the sensor documentation refers to it as universal time. Its vb net, I've corrected question. TYCobb - I read that question doesn't answer my question (I don't think) – Chris Sep 01 '17 at 15:15
  • 1
    Then it is simple arithmetic not unlike the link provided. Create a DateTime var for the start date (1/1/1904 00:00:00 UTC) add the value it gives you as seconds `myEpochStartDate.AddSeconds(value)` then `.ToLocalTime()`. Same principal as converting a Unix epoch date value to a NET one – Ňɏssa Pøngjǣrdenlarp Sep 01 '17 at 15:19

1 Answers1

0

Values which return the number of ticks or seconds since an arbitrary date are known as Epoch Dates. The most common one is the Unix Epoch which is the number of seconds (milliseconds in some cases) since January 1, 1970 UTC.

To convert it, you do essentially what the post describes for Excel: add that many seconds to a DateTime variable representing the base 1/1/1964 00:00:00.0 UTC date.

Private Function SensorEpochToDate(value As Long) As DateTime
    ' remove the 
    Return New DateTime(1904, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).
                AddSeconds(value).ToLocalTime()
End Function

You can remove the .ToLocalTime() to keep it as UTC.

Testing:

' RDG is a random data generator
'   pick a random date from 1/1/1970 to today 
Dim randomDate = DateTime.SpecifyKind(RDG.GetDate(DateType.UnixEpoch), DateTimeKind.Utc)
Console.WriteLine("   Selected Date: {0} (UTC)", randomDate.ToString())
' convert/emulate a sensor date 
Dim sensorDate = DateToSensorValue(randomDate)


Dim realDate = SensorEpochToDate(sensorDate)
Console.WriteLine("Round trip value: {0} (Local)", realDate.ToString())

Results:

Selected Date: 8/22/1994 7:23:00 PM (UTC)
Round trip value: 8/22/1994 5:23:00 PM (Local)

It might be nice to make it an extension method to make it easier to use, but as an integer type it would show up for too many variables for my taste.

Ňɏssa Pøngjǣrdenlarp
  • 38,411
  • 12
  • 59
  • 178