Right, so there I was, porting a small tool I once wrote from MFC to C# and trying to extend it. In my work I occasionally deal with Unix timestamps and I need to be able to convert them easily, so I wanted to add that functionality to my tool. But then I ran into a problem. You see, the .NET framework knows two kinds of timestamps. Ticks, which is the time since january 1st 0001 in 100 nano-second increments and FileTime, which is the time since january 1st 1601 in 100 nano-second increments. Neither of which maps to the timestamp used on Unix, which is the number of seconds since january 1st 1970.
First I Googled a bit and noticed the question had been asked before a few times, but I could not find an answer quick enough, so it looked like I had to do it myself. Fortunatly, it’s not that hard.
From Unix to .NET
This is the most simple. Create a DateTime object with the date of january 1st 1970 (12 AM) and just use the AddSeconds method to add the Unix timestamp:
public static System.DateTime UnixToDotNet(int unixTimestamp)
{
System.DateTime date = System.DateTime.Parse("1/1/1970");
return date.AddSeconds(unixTimestamp);
}
From .NET to Unix
The other way around is a bit harder, but not much. First create a TimeSpan object to cover the time from january 1st 0001 to january 1st 1970. This is the amount of time we want to ignore, because Unix time starts from january 1st 1970.
Substract that timespan from the .NET time you have and then divide the resulting Ticks, representing the time since januray 1st 1970, by 10 million. That gives you the time in seconds, which is the Unix format:
public static int DotNetToUnix(System.DateTime dotNetTimestamp)
{
System.TimeSpan span = new System.TimeSpan(System.DateTime.Parse("1/1/1970").Ticks);
System.DateTime time = dotNetTimestamp.Subtract(span);
int t = (int)(time.Ticks / 10000000);
return(t);
}
Easy enough.