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