C# - Convert DateTime to Long and Vice Versa

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

commit cd3eb8b · authored · 1 min read

C# - Convert DateTime to Long and Vice Versa

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;
}

local graph · open full graph

"C# - Convert DateTime to Long and Vice Versa" is connected to the topics C# and related to 7 other entries. NDepend - The Best-in-class Static Code Analyzer for Dotnet NDepend - The Best-in-class… C# - Get Last N characters from a string C# - Get Last N characters … C# - Get Web.Config Connection String in a Class Library C# - Get Web.Config Connect… Using AutoMapper in a .NET Core Class Library Using AutoMapper in a .NET … Check if string is Arabic - C# Check if string is Arabic -… Truncate String Without Word Break Truncate String Without Wor… Mask String Mask String C# #c-sharp C# - Convert DateTime to Long and…

comments

loading discussion…