在C#中解析unix时间

发布于 2024-08-09 21:23:19 字数 140 浏览 6 评论 0原文

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

Is there a way to quickly / easily parse Unix time in C# ? I'm brand new at the language, so if this is a painfully obvious question, I apologize. IE I have a string in the format [seconds since Epoch].[milliseconds]. Is there an equivalent to Java's SimpleDateFormat in C# ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

深巷少女 2024-08-16 21:23:19

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

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”而不是“x,y”的形式,您应该使用如上所示的不变区域性,以确保“.”。被解析为小数点
  • 您应该在 DateTime 构造函数中指定 UTC,以确保它不会认为它是本地时间。
  • 如果您使用的是 .NET 3.5 或更高版本,您可能需要考虑使用 DateTimeOffset 而不是 DateTime

Simplest way is probably to use something like:

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

Three things to note:

  • If your strings are definitely of the form "x.y" rather than "x,y" you should use the invariant culture as shown above, to make sure that "." is parsed as a decimal point
  • You should specify UTC in the DateTime constructor to make sure it doesn't think it's a local time.
  • If you're using .NET 3.5 or higher, you might want to consider using DateTimeOffset instead of DateTime.
烟燃烟灭 2024-08-16 21:23:19

这是 C# 中人们经常做的事情,但没有相应的库。

我创建了这个迷你库 https://gist.github.com/1095252 来让我的生活变得美好(我希望你的也是)更容易。

This is a very common thing people in C# do, yet there is no library for that.

I created this mini library https://gist.github.com/1095252 to make my life (I hope yours too) easier.

赴月观长安 2024-08-16 21:23:19
// 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/KB/cs/timestamp.aspx

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

颜漓半夏 2024-08-16 21:23:19
var date = (new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc))
               .AddSeconds(
               double.Parse(yourString, CultureInfo.InvariantCulture));
var date = (new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc))
               .AddSeconds(
               double.Parse(yourString, CultureInfo.InvariantCulture));
遮了一弯 2024-08-16 21:23:19

我意识到这是一个相当老的问题,但我想我应该发布我的解决方案,该解决方案使用 Nodatime 的 Instant 类,其中 有一个专门用于此目的的方法

Instant.FromSecondsSinceUnixEpoch(longSecondsSinceEpoch).ToDateTimeUtc();

我完全明白,也许加入 Nodatime 对某些人来说可能会很沉重。对于我的项目,依赖性膨胀不是主要问题,我宁愿依赖维护的库解决方案,而不必维护自己的解决方案。

I realize this is a fairly old question but I figured I'd post my solution which used Nodatime's Instant class which has a method specifically for this.

Instant.FromSecondsSinceUnixEpoch(longSecondsSinceEpoch).ToDateTimeUtc();

I totally get that maybe pulling in Nodatime might be heavy for some folks. For my projects where dependency bloat isn't a major concern I'd rather rely on maintained library solutions rather than having to maintain my own.

芯好空 2024-08-16 21:23:19

从 .NET 4.6 开始,您可以使用 DateTimeOffset.FromUnixTimeSeconds()DateTimeOffset.FromUnixTimeMilliseconds()

long unixTime = 1600000000;
DateTimeOffset dto = DateTimeOffset.FromUnixTimeSeconds(unixTime);
DateTime dt = dto.DateTime;

Since .NET 4.6, you can use DateTimeOffset.FromUnixTimeSeconds() and DateTimeOffset.FromUnixTimeMilliseconds():

long unixTime = 1600000000;
DateTimeOffset dto = DateTimeOffset.FromUnixTimeSeconds(unixTime);
DateTime dt = dto.DateTime;
情何以堪。 2024-08-16 21:23:19

这是来自 Stefan Henke 的博客文章< /a>:

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

This is from 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;
}
羞稚 2024-08-16 21:23:19

MSDN DateTime 文档万岁!另请参阅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));

Hooray for MSDN DateTime docs! Also see 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));
沉睡月亮 2024-08-16 21:23:19

这是一个方便的扩展方法

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

Here it is as a handy extension method

  public static DateTime UnixTime(this string timestamp)
    {
        var dateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0);
        return dateTime.AddSeconds(int.Parse(timestamp));
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文