Иногда нужно конвертировать время из System.DateTime в UNIX timestamp или наоборот.

Получение текущего времени в формате UNIX timestamp:


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;
}

Источник: http://blogs.msdn.com/brada/archive/2004/03/20/93332.aspx

Конвертация из UNIX timestamp в System.DateTime:


// This is an example of a UNIX timestamp for the date/time 11-04-2005 09:25.
double timestamp = 1113211532;

// First make a System.DateTime equivalent to the UNIX Epoch.
System.DateTime dateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0);

// Add the number of seconds in UNIX timestamp to be converted.
dateTime = dateTime.AddSeconds(timestamp);

// The dateTime now contains the right date/time so to format the string,
// use the standard formatting methods of the DateTime object.
string printDate = dateTime.ToShortDateString() +" "+ dateTime.ToShortTimeString();

// Print the date and time
System.Console.WriteLine(printDate);

Источник: http://www.codeproject.com/csharp/timestamp.asp

Получение текущего времени в формате UNIX timestamp в одной строке:


int epoch = (int)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds;

Источник: http://snippets.dzone.com/posts/show/3236

1 звезда2 звезд3 звезд4 звезд5 звезд (1 голосов, средний: 5 из 5)
Загрузка ... Загрузка ...