Parsing Decimal to DateTime in multiple date formats with a leading zero stripped out?

So I think there is a simple answer to this problem. Essentially I am getting a decimal storage of a DateTime from a database that is in essence '9062017'. I was wanting to create a decimal extension method to account for decimals and parsing and do variable formats for an extensible DateTime. I was playing around with the logic, yet it keeps not working. I was looking up a few threads on SO like this: Parse datetime in multiple formats. But it's not explaining what I think would just work and does not.

static void Main(string[] args)
{
  DateTime d = new DateTime(2017, 9, 6);
  //Cool what I would expect to show the day position with two digits and the month uses one if needed else it will go to two if needed.
  Console.WriteLine(d.ToString("Mddyyyy"));

  //I can parse out an int and see it is exactly as above.
  int i = Int32.Parse(d.ToString("Mddyyyy"));
  Console.WriteLine(i.ToString());

  DateTime dt;
  string[] formats = { "Mddyyyy", "MMddyyyy" };
  //Keeps default min value of DateTime and ignores parsing regardless of formats done in the first arg changes, the seconds formats to apply, or cultural changes.
  DateTime.TryParseExact(i.ToString(), formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out dt);

  Console.WriteLine(dt);


  //Console.WriteLine(i);
  Console.ReadLine();
}
Jon Skeet
people
quotationmark

I think you should avoid the string conversion entirely. It's pointless and error prone. It's much simpler just to do the maths:

public static DateTime Int32ToDateTime(int value)
{
    int year = value % 10000;
    int day = (value / 10000) % 100;
    int month = value / 1000000;
    // Specify whatever kind is appropriate; it's unclear from the question.
    return new DateTime(year, month, day);
}

public static int DateTimeToInt32(DateTime date) =>
    date.Year + (date.Day * 10000) + (date.Month * 1000000);

I wouldn't use an extension method for this. It's not appropriate for all integers. You should be really, really clear when you're doing this. If you have multiple numeric formats, you could have an interface an multiple implementations:

public interface IDateTimeInt32Converter
{
    DateTime Int32ToDateTime(int value);
    int Int32ToDateTime(DateTime date);
}

public class YearMonthDayConverter : IDateTimeInt32Converter
{
    // etc
}

// Ditto for MonthDayYearConverter and DayMonthYearConverter

people

See more on this question at Stackoverflow