在C#中解析unix时间

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

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

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

需要注意三点:

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

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

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

 // 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); 

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

 var date = (new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)) .AddSeconds( double.Parse(yourString, CultureInfo.InvariantCulture)); 

这是来自Stefan Henke的博客文章 :

 private string conv_Timestamp2Date (int Timestamp) { // calculate from Unix epoch System.DateTime dateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0); // add seconds to timestamp dateTime = dateTime.AddSeconds(Timestamp); string Date = dateTime.ToShortDateString() +", "+ dateTime.ToShortTimeString(); return Date; } 

Hooray for MSDN DateTime docs ! 另见TimeSpan 。

 // 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(numSeconds); // Then add the number of milliseconds dateTime = dateTime.Add(TimeSpan.FromMilliseconds(numMilliseconds)); 

我意识到这是一个相当古老的问题,但我想我会发布我的解决方案,该解决方案使用了Nodatime的 Instant类,该类具有专门针对此的方法 。

 Instant.FromSecondsSinceUnixEpoch(longSecondsSinceEpoch).ToDateTimeUtc(); 

我完全明白,诺达提可能对某些人来说很重要。 对于我的项目,其中依赖膨胀不是主要问题,我宁愿依赖维护的库解决方案,而不是必须维护我自己的。

这是一个方便的扩展方法

  public static DateTime UnixTime(this string timestamp) { var dateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0); return dateTime.AddSeconds(int.Parse(timestamp)); }