For some reasons, some programmer might store time values as Unix timestamp in database instead of standard SQL DateTime data type. The main reason to store time values as Unix timestamp is unknown but what I guess is for maximum database compatibility. Some old database does not support SQL DateTime data type.
Converting Unix time to C# or .Net DateTime and vice versa is pretty simple. The unix time is simple the difference between the wanted DateTime value with the DateTime value of 1st January 1970. Here is the code in C#:
using System;
namespace snippetit.sample
{
struct UnixTime
{
private static DateTime BEGIN_UTC = new DateTime(1970, 1, 1);
private long utValue;
public UnixTime(long seconds)
{
utValue = seconds;
}
public UnixTime(DateTime dateTime)
{
this.DateTime = dateTime;
}
public long Value
{
get { return utValue; }
set { utValue = value; }
}
public DateTime DateTime
{
get { return BEGIN_UTC.AddSeconds((long)utValue); }
set { utValue = (long)((TimeSpan)(value - BEGIN_UTC)).TotalSeconds; }
}
public override string ToString()
{
return DateTime.ToString("yyy-MM-dd HH:mm:ss"); ;
}
}
}
[…] C#: Unix Time to .Net DateTime and Vice Versa […]