3
votes

I'm having a little trouble converting nanoseconds to DateTime so i can use the Google Fit API (https://developers.google.com/fit/rest/v1/reference/users/dataSources/datasets/get)

Dataset identifier that is a composite of the minimum data point start time and maximum data point end time represented as nanoseconds from the epoch. The ID is formatted like: "startTime-endTime" where startTime and endTime are 64 bit integers.

I was able to convert from datetime to Nanoseconds this way

DateTime zuluTime = ssDatetime.ToUniversalTime();
DateTime unixEpoch = new DateTime(1970, 1, 1);
ssNanoSeconds = (Int32)(zuluTime.Subtract(unixEpoch)).TotalSeconds + "000000000";

But now i need to convert nanoseconds to DateTime. How can i do it?

2
Ticks resolution is 100 nanoseconds. You can add it with AddTicks method.Soner Gönül
Nanoseconds since when? 1970-01-01T00:00:00Z or some time else?Jon Hanna

2 Answers

6
votes

Use AddTicks method. Don't forget to divide nanoseconds by 100 to get ticks.

long nanoseconds = 1449491983090000000;
DateTime epochTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
DateTime result = epochTime.AddTicks(nanoseconds / 100);
2
votes

Ticks property represents 100 nanoseconds. So how about :

 var ssNanoSeconds = ((zuluTime.Subtract(unixEpoch)).Ticks / 100)

From nanoseconds to DateTime

 DateTime dateTime = new DateTime(1970, 1, 1).AddTicks(nanoSeconds * 100) ;