As I learn to automate

Wednesday, September 27, 2006

Seconds since the Unix epoch in C#

Recently, I had to get “seconds since unix epoch” for a particular application. You can google for various articles about this. But, here is some code that I ended up with some minor but critical modification:

http://blogs.msdn.com/brada/archive/2004/03/20/93332.aspx

This was the last word on the topic:

public long GetEpochTime()
{
DateTime dtCurTime = DateTime.Now;
DateTime dtEpochStartTime = Convert.ToDateTime("1/1/1970 8:00:00 AM");
TimeSpan ts = dtCurTime.Subtract(dtEpochStartTime);
long epochtime; epochtime = ((((((ts.Days * 24) + ts.Hours) * 60) + ts.Minutes) * 60) + ts.Seconds);
return epochtime;
}
But, this is what I thought works right:

public long GetEpochTime()
{
DateTime dtCurTime = DateTime.UtcNow;
DateTime dtEpochStartTime = Convert.ToDateTime("1/1/1970 0:00:00 AM");
TimeSpan ts = dtCurTime.Subtract(dtEpochStartTime);
long epochtime; epochtime = ((((((ts.Days * 24) + ts.Hours) * 60) + ts.Minutes) * 60) + ts.Seconds);
return epochtime;
}

Two changes:
Start time is: 1/1/1970 0:00:00 AM
Curr time is: UtcNow