1

How can I convert nanoseconds to Datetimeoffset?

I tried date time

long nanoseconds = 1449491983090000000;
DateTime epochTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Local);
DateTime result1 = epochTime.AddTicks(nanoseconds / 100);

DateTime epochTimfe = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
DateTime result2 = epochTime.AddTicks(nanoseconds / 100);

Both result1 and result2 are giving me GMT time. i.e.,

12/7/2015 12:39:43 PM

I verified that from here

Can anyone help me how to convert nanoseconds to DateTimeOffset ?

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
TheDeveloper
  • 1,127
  • 1
  • 18
  • 55
  • You can try to use `DateTimeOffset.FromUnixTimeMilliseconds` method, add look at this thread [How can I convert a Unix timestamp to DateTime and vice versa?](https://stackoverflow.com/questions/249760/how-can-i-convert-a-unix-timestamp-to-datetime-and-vice-versa) – Pavel Anikhouski Jan 09 '20 at 14:37
  • Does this answer your question? [How can I convert a Unix timestamp to DateTime and vice versa?](https://stackoverflow.com/questions/249760/how-can-i-convert-a-unix-timestamp-to-datetime-and-vice-versa) – Heretic Monkey Jan 09 '20 at 14:41
  • Nanoseconds are a unit of time. DateTimeOffsets represent an instant in time (with an associated time zone). What you are asking is something like "I want to convert from km to location". If you peg a starting position and a direction (which isn't necessary for time, there's only one direction), you can do it, but you need a starting point (an epoch in time-speek). You can get a TimeSpan from nanoseconds pretty easily. If you add that to a starting dateTimeOffset, you should be off to the races – Flydog57 Jan 09 '20 at 14:45
  • Alternatively, once you actually have a correct `DateTime` (by whatever method), you can simply pass it to the `DateTimeOffset` constructor and get the `.ToLocalTime()` of it. This requires that the `DateTimeKind` is correct. – Jeroen Mostert Jan 09 '20 at 14:45

1 Answers1

3

You could just construct an instance of DateTimeOffset in UTC, add the nanoseconds, then call ToLocalTime to get the local version.

long nanoseconds = 1449491983090000000;
var epochTime = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero);
var utc = epochTime.AddTicks(nanoseconds / 100);
var local = utc.ToLocalTime();
Joshua Robinson
  • 3,399
  • 7
  • 22