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)
需要注意三点:
DateTime构造函数中指定UTC,以确保它不认为它是本地时间.DateTimeOffset而不是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);
Run Code Online (Sandbox Code Playgroud)
Surce:http://www.codeproject.com/KB/cs/timestamp.aspx