解析Unix时间在C# [英] Parsing unix time in C#

查看:168
本文介绍了解析Unix时间在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以快速/轻松地分析Unix时间在C#中?我是全新的语言,所以如果这是一个非常明显的问题,我很抱歉。 IE浏览器我有格式的字符串[纪元以来的秒数]。[毫秒]。是否有一个相当于Java的SimpleDateFormat的在C#?

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# ?

推荐答案

最简单的方法可能是使用这样的:

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

三点注意事项:


  • 如果你的字符串是绝对的形式是xy格式的,而不是X,Y你应该使用固定区域性如上图所示,以确保的。被解析为一个小数点

  • 您应该在的DateTime 构造指定UTC,以确保它不认为这是一个本地时间。

  • 如果您正在使用.NET 3.5或更高版本,你可能要考虑使用<一个href=\"http://msdn.microsoft.com/en-us/library/system.datetimeoffset.aspx\"><$c$c>DateTimeOffset而不是的DateTime

  • 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.

这篇关于解析Unix时间在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆