c-sharp

C# - Convert DateTime to Long and Vice Versa

Transform datetime to long or long to datetime in C#.

Abhith Rajan
Abhith RajanOctober 29, 2019 · 1 min read · Last Updated:

Story behind this post is when I started working with an existing MSSQL DB, I had to convert the DateTime to long since action auditing fields such as CreationTime, LastUpdated etc was stored as numeric.

eg, 20191028091320.

First of all, I don’t like storing DateTime in numeric format like above, which brings so much overhead during dealing with the same field, like querying based on date, formatting for displaying etc.

The way I handled these conversions given below,

DateTime to Long

long.Parse(DateTime.UtcNow.ToString("yyyyMMddHHmmss"))

Long to DateTime

The below code can handle 14 digits (eg. 20191028091320), 16 digits (eg. 2019102809132000 ) and 8 digits (eg. 20191028).

private static DateTime? GetDateTimeFromInt(long? dateAsLong, bool hasTime = true)
{
    if (dateAsLong.HasValue && dateAsLong > 0)
    {
        if (hasTime)
        {
            // sometimes input is 14 digit and sometimes 16
            var numberOfDigits = (int)Math.Floor(Math.Log10(dateAsLong.Value) + 1);

            if (numberOfDigits > 14)
            {
                dateAsLong /= (int)Math.Pow(10, (numberOfDigits - 14));
            }
        }

        if (DateTime.TryParseExact(dateAsLong.ToString(), hasTime ? "yyyyMMddHHmmss" : "yyyyMMdd",
                                  CultureInfo.InvariantCulture,
                                  DateTimeStyles.None, out DateTime dt))
        {
            return dt;
        }
    }

    return null;
}

This page is open source. Noticed a typo? Or something unclear?
Improve this page on GitHub


Abhith Rajan

Written byAbhith Rajan
Abhith Rajan is a software engineer by day and a full-stack developer by night. He's coding for almost a decade now. He codes 🧑‍💻, write ✍️, learn 📖 and advocate 👍.
Connect

Is this page helpful?

Related SnippetsView All

Related ArticlesView All

Related VideosView All

C# Project Management in VS Code [Pt 3] | C# and .NET Development in VS Code for Beginners

Installing VS Code and C# Dev Kit [Pt 2] | C# and .NET Development in VS Code for Beginners

What is VS Code and C# Dev Kit? [Pt 1] | C# and .NET Development in VS Code for Beginners