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
var date = (new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc))
.AddSeconds(
double.Parse(yourString, CultureInfo.InvariantCulture));
// 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
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;
}
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));
}
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.
Since .NET 4.6, you can use DateTimeOffset.FromUnixTimeSeconds()
and DateTimeOffset.FromUnixTimeMilliseconds()
:
long unixTime = 1600000000;
DateTimeOffset dto = DateTimeOffset.FromUnixTimeSeconds(unixTime);
DateTime dt = dto.DateTime;