From Milliseconds to DateTime with C Sharp

How to convert milliseconds to DateTime with C#.

Last updated on December 27, 2019. Created on December 23, 2019.

Converting an arbitrary duration of time from milliseconds to C#'s built-in System.DateTime is not too bad. Why would you do this? I don't know—probably to lazily format the time for display purposes. Now, here's code for the conversion:

using System;

namespace SomeNamespace
{
    static class Util
    {
        /// <summary>Returns a DateTime provided the elapsed milliseconds,
        /// year, month, day, and DateTimeKind.</summary>
        public static DateTime ToDateTime(
            float milliseconds,
            int year = 1970,
            int month = 1,
            int day = 1,
            DateTimeKind dateTimeKind = DateTimeKind.Local
        ) => new DateTime(year, month, day, 0, 0, 0, 0, dateTimeKind)
            .AddMilliseconds(milliseconds);
    }
}

The milliseconds parameter must be passed when calling ToDateTime, but everything else is optional. I opted to default the year to 1970 in lieu of Unix time. Note that if you are working with Unix time, it's a special case where, rather than using the custom wrapper method declared above, you would prefer this one-liner instead:

DateTimeOffset.FromUnixTimeMilliseconds(milliseconds).DateTime; // or .UtcDateTime

Otherwise, our custom function allows initialization to the year 4000, which may be helpful if you're making a game. The month and day are both defaulted to 1, which also helps illustrate that they are NOT zero-based indices. After all, would it make sense to have a zeroth day of the month? Uh, well, I'm personally not in favor of that. Also, pay attention to the fact that I default to DateTimeKind.Local, but you're welcome to also use DateTimeKind.Utc or DateTimeKind.Unspecified depending on your needs.

Those other zeroes I initialize the returned DateTime with are respectively the hour, minute, second, and millisecond. In their case, the zero-based index makes sense. Generally they would be initialized with zero in this context, but you're welcome to modify the wrapping ToDateTime method to suit your use case.

That's it!

© Reese Schultz

My code is released under the MIT license.