4

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?

Sergii Zhevzhyk
  • 4,074
  • 22
  • 28
Luis
  • 2,665
  • 8
  • 44
  • 70

3 Answers3

8

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);
Sergii Zhevzhyk
  • 4,074
  • 22
  • 28
2

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) ; 
Perfect28
  • 11,089
  • 3
  • 25
  • 45
  • Your `new DateTime` is starting with `DateTime.MinValue`, not the unix epoch. – Jon Hanna Dec 07 '15 at 12:25
  • Also the nanoSeconds in the first line need to be multiplied by 100 and divided in the second example. so: `..(zuluTime.Subtract(unixEpoch)).Ticks * 100 ..` and `.AddTicks(nanoSeconds / 100)` – Robert Sirre Dec 17 '18 at 14:16
0

To convert nanoseconds to a DateTime object, you can do the following:

Divide the nanoseconds value by 1,000,000,000 to get the equivalent number of seconds. Create a DateTime object representing the Unix epoch (January 1, 1970). Add the number of seconds to the Unix epoch to get the desired DateTime object.

long nanoseconds = 1234567890123; // nanoseconds value to convert

// Divide the nanoseconds value by 1,000,000,000 to get the equivalent number of seconds
int seconds = (int)(nanoseconds / 1000000000);

// Create a DateTime object representing the Unix epoch (January 1, 1970)
DateTime unixEpoch = new DateTime(1970, 1, 1);

// Add the number of seconds to the Unix epoch to get the desired DateTime object
DateTime datetime = unixEpoch.AddSeconds(seconds);

Note that this will only work correctly if the nanoseconds value is within the range of values that can be represented by a DateTime object (approximately 292 million years before or after the Unix epoch). If the nanoseconds value is outside of this range, the resulting DateTime object will not be accurate.