21

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

Alex Marshall
  • 10,162
  • 15
  • 72
  • 117

9 Answers9

43

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.
John Gietzen
  • 48,783
  • 32
  • 145
  • 190
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
6

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.

Andrius Bentkus
  • 1,392
  • 11
  • 25
5
// 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

Chris Ballance
  • 33,810
  • 26
  • 104
  • 151
4
var date = (new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc))
               .AddSeconds(
               double.Parse(yourString, CultureInfo.InvariantCulture));
John Gietzen
  • 48,783
  • 32
  • 145
  • 190
  • 3
    That will end up with a DateTimeKind of unspecified, I believe. It will also use the local culture to determine the decimal point format. – Jon Skeet Nov 04 '09 at 14:54
2

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.

ojintoad
  • 433
  • 3
  • 6
2

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

long unixTime = 1600000000;
DateTimeOffset dto = DateTimeOffset.FromUnixTimeSeconds(unixTime);
DateTime dt = dto.DateTime;
Christian Davén
  • 16,713
  • 12
  • 64
  • 77
1

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));
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
  • 2
    The edited version of your post is fine. However, the first version was really unhelpful, since the linked MSDN page does not have a sample for UNIX timestamps, nor does DateTime have a built-in function you could have found through that page. Now that you've edited the answer, it's just the same as the others. – OregonGhost Nov 04 '09 at 14:59
1

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;
}
Thorsten79
  • 10,038
  • 6
  • 38
  • 54
0

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