0
votes

What is the most elegant way of getting the following:

Starting from today's date, return an enumerable that would be the following:

July 1st July 15th August 1st August 15th September 1st September 15th October 1st October 15th

Should account for things like if it's the end of the year, then it goes December 15 January 1st.

1

1 Answers

7
votes

Your title asked for a string, but the question text asked for an enumerable. Which is it?

Anyway, here's the enumerable:

public IEnumerable<DateTime> GetPaymentDates()
{
   DateTime first = new DateTime(DateTime.Today.Year, DateTime.Today.Month, 1);
   DateTime fifteenth = first.AddDays(14);

   for (int i=0;i<4;i++)
   {
      yield return first;
      yield return fifteenth;

      first = first.AddMonths(1);
      fifteenth = first.AddDays(14);
   }
}

or a version that returns the strings:

public IEnumerable<string> GetPaymentDates()
{
   DateTime current = new DateTime(DateTime.Today.Year, DateTime.Today.Month, 1);

   for (int i=0;i<4;i++)
   {
      yield return current.ToString("MMMM 1st");
      yield return current.ToString("MMMM 15th");

      current = current.AddMonths(1);
   }
}