【发布时间】:2009-11-04 14:46:49
【问题描述】:
有没有办法在 C# 中快速/轻松地解析 Unix 时间?我是这门语言的新手,所以如果这是一个非常明显的问题,我深表歉意。 IE 我有一个格式为 [自纪元以来的秒数].[毫秒] 的字符串。 C# 中是否有与 Java 的 SimpleDateFormat 等价的功能?
【问题讨论】:
标签: c# unix-timestamp
有没有办法在 C# 中快速/轻松地解析 Unix 时间?我是这门语言的新手,所以如果这是一个非常明显的问题,我深表歉意。 IE 我有一个格式为 [自纪元以来的秒数].[毫秒] 的字符串。 C# 中是否有与 Java 的 SimpleDateFormat 等价的功能?
【问题讨论】:
标签: c# unix-timestamp
最简单的方法可能是使用类似的东西:
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);
}
注意三点:
DateTime 构造函数中指定 UTC,以确保它认为不是当地时间。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);
【讨论】:
var date = (new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc))
.AddSeconds(
double.Parse(yourString, CultureInfo.InvariantCulture));
【讨论】:
我意识到这是一个相当老的问题,但我想我会发布我的解决方案,它使用 Nodatime's Instant 类 has a method specifically for this。
Instant.FromSecondsSinceUnixEpoch(longSecondsSinceEpoch).ToDateTimeUtc();
我完全明白,对于某些人来说,加入 Nodatime 可能会很沉重。对于依赖膨胀不是主要问题的项目,我宁愿依赖维护的库解决方案,而不是自己维护。
【讨论】:
从 .NET 4.6 开始,您可以使用 DateTimeOffset.FromUnixTimeSeconds() 和 DateTimeOffset.FromUnixTimeMilliseconds():
long unixTime = 1600000000;
DateTimeOffset dto = DateTimeOffset.FromUnixTimeSeconds(unixTime);
DateTime dt = dto.DateTime;
【讨论】:
这是来自a blog posting by 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;
}
【讨论】:
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));
【讨论】:
这是一个方便的扩展方法
public static DateTime UnixTime(this string timestamp)
{
var dateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0);
return dateTime.AddSeconds(int.Parse(timestamp));
}
【讨论】: