Parsing unix time in C#

后端 未结 9 625
悲&欢浪女
悲&欢浪女 2020-11-30 10:13

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 th

相关标签:
9条回答
  • 2020-11-30 10:29
    var date = (new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc))
                   .AddSeconds(
                   double.Parse(yourString, CultureInfo.InvariantCulture));
    
    0 讨论(0)
  • 2020-11-30 10:32
    // 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

    0 讨论(0)
  • 2020-11-30 10:34

    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;
    }
    
    0 讨论(0)
  • 2020-11-30 10:34

    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));
        }
    
    0 讨论(0)
  • 2020-11-30 10:36

    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.

    0 讨论(0)
  • 2020-11-30 10:39

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

    long unixTime = 1600000000;
    DateTimeOffset dto = DateTimeOffset.FromUnixTimeSeconds(unixTime);
    DateTime dt = dto.DateTime;
    
    0 讨论(0)
提交回复
热议问题