Парсинг времени Unix в C#

Я всегда пользовался Библиотекой SharpZip.

Вот ссылка

19
задан Alex Marshall 4 November 2009 в 14:46
поделиться

5 ответов

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.
40
ответ дан 30 November 2019 в 02:16
поделиться
// 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

5
ответ дан 30 November 2019 в 02:16
поделиться
var date = (new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc))
               .AddSeconds(
               double.Parse(yourString, CultureInfo.InvariantCulture));
4
ответ дан 30 November 2019 в 02:16
поделиться

Это из сообщения в блоге Стефана Хенке :

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;
}
1
ответ дан 30 November 2019 в 02:16
поделиться

Ура для документов 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));
1
ответ дан 30 November 2019 в 02:16
поделиться
Другие вопросы по тегам:

Похожие вопросы: