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);
}
Three things to note:
DateTime
constructor to make sure it doesn't think it's a local time.DateTimeOffset
instead of DateTime
.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.
// 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
var date = (new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc))
.AddSeconds(
double.Parse(yourString, CultureInfo.InvariantCulture));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With