在C#中解析unix时间

Ale*_*all 19 c# unix-timestamp

有没有办法在C#中快速/轻松地解析Unix时间?我对这种语言很陌生,所以如果这是一个非常明显的问题,我会道歉.IE我有一个格式的字符串[自纪元以来的秒数].[毫秒].在C#中是否有Java的SimpleDateFormat?

Jon*_*eet 40

最简单的方法可能是使用类似的东西:

private static readonly DateTime Epoch = new DateTime(1970, 1, 1, 0, 0, 0, 
                                                      DateTimeKind.Utc);

...
public static DateTime UnixTimeToDateTime(string text)
{
    double seconds = double.Parse(text, CultureInfo.InvariantCulture);
    return Epoch.AddSeconds(seconds);
}
Run Code Online (Sandbox Code Playgroud)

需要注意三点:

  • 如果你的字符串肯定是"xy"形式而不是"x,y",你应该使用如上所示的不变文化,以确保"." 被解析为小数点
  • 您应该在DateTime构造函数中指定UTC,以确保它不认为它是本地时间.
  • 如果您使用的是.NET 3.5或更高版本,则可能需要考虑使用DateTimeOffset而不是DateTime.


And*_*kus 6

这是C#中人们非常普遍的事情,但是没有这个库.

我创建了这个迷你图书馆https://gist.github.com/1095252,让我的生活(我希望你的生活)更轻松.


Chr*_*nce 5

// 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);
Run Code Online (Sandbox Code Playgroud)

Surce:http://www.codeproject.com/KB/cs/timestamp.aspx