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
1long.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).
1private static DateTime? GetDateTimeFromInt(long? dateAsLong, bool hasTime = true)2{3 if (dateAsLong.HasValue && dateAsLong > 0)4 {5 if (hasTime)6 {7 // sometimes input is 14 digit and sometimes 168 var numberOfDigits = (int)Math.Floor(Math.Log10(dateAsLong.Value) + 1);910 if (numberOfDigits > 14)11 {12 dateAsLong /= (int)Math.Pow(10, (numberOfDigits - 14));13 }14 }1516 if (DateTime.TryParseExact(dateAsLong.ToString(), hasTime ? "yyyyMMddHHmmss" : "yyyyMMdd",17 CultureInfo.InvariantCulture,18 DateTimeStyles.None, out DateTime dt))19 {20 return dt;21 }22 }2324 return null;25}