How to convert Milliseconds to date format in C#?

danny picture danny · Sep 7, 2011 · Viewed 82.6k times · Source

In C# how can I convert Unix-style timestamp to yyyy-MM-ddThh:mm:ssZ?

Answer

Jay picture Jay · Sep 7, 2011

Start by converting your milliseconds to a TimeSpan:

var time = TimeSpan.FromMilliseconds(milliseconds);

Now, in .NET 4 you can call .ToString() with a format string argument. See http://msdn.microsoft.com/en-us/library/system.timespan.tostring.aspx

In previous versions of .NET, you'll have to manually construct the formatted string from the TimeSpan's properties.