Converting a Date to an Integer in C#

I needed to convert a date like “04-Jan-2014” into an integer like 3 where the integer is the 0-based number from a given start date (like January 1, 2014). In other words, 01-Jan-2014 maps to 0, 02-Jan-2014 maps to 1, 03-Jan-2014 maps to 2, 04-Jan-2014 maps to 3, and so on. Working with dates is always a little bit awkward for me because I don’t do it very often. I did an Internet search for “C# convert date to integer” and found many pointers to various developer blogs, most of them with pretty decent solutions. My point is I didn’t have to solve the problem from scratch; I was able to use information I found on the Internet and just modify it slightly to meet my needs.

In my case I wanted my starting date to be fixed at 15-Jul-2013. Here is a C# function that converts a date to a 0-based integer which is the number of days after the start date:

static int DayNum(string date)
{
  DateTime start = DateTime.Parse("15-Jul-2013");
  DateTime dt = DateTime.Parse(date);
  TimeSpan t = dt - start;
  return (int)t.TotalDays;
}

The function could be called like this:

string date = "30-Sep-2013";
int n = DayNum(date);
Console.WriteLine("30-Sept-2013 as an int = " + n);

The DateTime.Parse method can handle many different formats so I can also call like:

string date = "09/30/2013";
int n = DayNum(date);

If I would have needed more flexibility to deal with different starting dates, I could have passed the start date in as a parameter:

static int DayNum(string date, string startDate)
{
  DateTime start = DateTime.Parse startDate);
  DateTime dt = DateTime.Parse(date);
  TimeSpan t = dt - start;
  return (int)t.TotalDays;
}

But for my purposes the extra flexibility wasn’t needed because there was just a single start date that didn’t change. Additionally, I’d have to be careful about which date was which when passing to the function. When working with dates I always have to remind myself that there’s usually a simple solution to most problems.

This entry was posted in Machine Learning. Bookmark the permalink.