-1

I want to convert my datetime in C# (e.g. 2009-06-22 16:35:16.000) to something like this 1196550000000. I tried the following method but it fails.

public static double GetTimestamp(DateTime value)
{
    long ticks = DateTime.UtcNow.Ticks - DateTime.Parse(value.ToString()).Ticks;
    ticks /= 10000000; //Convert windows ticks to seconds
    Int64 timestamp = ticks;
    return timestamp;
}
AdrianHHH
  • 13,492
  • 16
  • 50
  • 87
  • 1
    `DateTime.Parse(value.ToString()).Ticks` equals `value.Ticks` in case of successful parse – fubo Jan 19 '17 at 10:35
  • 2
    Possible duplicate of [How to convert datetime to timestamp using C#/.NET (ignoring current timezone)](http://stackoverflow.com/questions/9814060/how-to-convert-datetime-to-timestamp-using-c-net-ignoring-current-timezone) – OmG Jan 19 '17 at 10:48

1 Answers1

0

First of all, you don't need to ToString() and Reparse the DateTime. If you want just the Date you can use the DateTime.Date property.

Then, this should be simple enough (using DateTime.Now as a reference point):

public static double GetTimestamp(DateTime value)
{
    return new TimeSpan(DateTime.UtcNow.Ticks - value.Ticks).TotalSeconds;
}

In case the parsing you did in your question did refer to extracting the date from the DateTime, you can use the following:

public static double GetTimestamp(DateTime value)
{
     return new TimeSpan(DateTime.UtcNow.Ticks - value.Date.Ticks).TotalSeconds;
}

EDIT : You appear to want some kind of posix time conversion which can be achieved like this :

private static readonly DateTime POSIXRoot = new DateTime(1970, 1, 1, 0, 0, 0, 0);
public static double GetPosixSeconds(DateTime value)
{
    return (value - POSIXRoot).TotalSeconds;
}

public static DateTime GetDateTime(double posixSeconds) {
    return POSIXRoot.AddSeconds(posixSeconds);
}
Bugs
  • 4,491
  • 9
  • 32
  • 41