I want to convert my datetime in C# (eg 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;
}
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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.