c-sharp |

C# - Convert DateTime to Long and Vice Versa

by Abhith RajanOctober 29, 2019 · 2 min read · Last Updated:
Share this

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 16
8 var numberOfDigits = (int)Math.Floor(Math.Log10(dateAsLong.Value) + 1);
9
10 if (numberOfDigits > 14)
11 {
12 dateAsLong /= (int)Math.Pow(10, (numberOfDigits - 14));
13 }
14 }
15
16 if (DateTime.TryParseExact(dateAsLong.ToString(), hasTime ? "yyyyMMddHHmmss" : "yyyyMMdd",
17 CultureInfo.InvariantCulture,
18 DateTimeStyles.None, out DateTime dt))
19 {
20 return dt;
21 }
22 }
23
24 return null;
25}

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

Abhith Rajan

Written by Abhith Rajan Buy me a coffee
Abhith Rajan is an aspiring software engineer with more than 6 years of experience and proven successful track record of delivering technology-based products and services.