Tuesday, September 4, 2007

Converting .NET DateTime to Unix timestamp

Here is sample code which you can use to convert from .NET DateTime to Unix timestamp time format. It is based on TimeSpan object properties, TimeSpan object can be got for example when you substract one DateTime object from another:


public static String GetNowTimestamp(bool withMilliseconds)
{
DateTime now = DateTime.Now.ToUniversalTime();
DateTime start = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

TimeSpan diff = DateTime.Now - start;
double value;
if (withMilliseconds)
{
value = diff.TotalMilliseconds;
}
else
{
value = diff.TotalSeconds;
}

decimal roundedVal = (decimal) Math.Round(value, 0);
return Convert.ToString(Convert.ToInt64(roundedVal));
}

No comments: