Rohit Gupta

Engaging talk on Microsoft Technologies ....My Resume

  Home  |   Contact  |   Syndication    |   Login
  41 Posts | 0 Stories | 52 Comments | 0 Trackbacks

News



Twitter












Archives

Image Galleries

Personal

I wrote these utility extension methods to get the previous quarter end/month end and next quarter end/month end values for Financial calculations.

Next Quarter End:

   1: public static DateTime NextQuarterEnd(this DateTime date)
   2: {
   3:     IEnumerable<DateTime> candidates =
   4:         QuartersInYear(date.Year).Union(QuartersInYear(date.Year + 1));
   5:     return candidates.Where(d => d.Subtract(date).Days > 0).First();            
   6: }
   7:  
   8: public static IEnumerable<DateTime> QuartersInYear(int year)
   9: {
  10:     return new List<DateTime>() {
  11:             new DateTime(year, 3, 31),
  12:             new DateTime(year, 6, 30),
  13:             new DateTime(year, 9, 30),
  14:             new DateTime(year, 12, 31),
  15:             };
  16: }
Last Quarter End:
   1: public static DateTime PreviousQuarterEnd(this DateTime date)
   2: {
   3:     IEnumerable<DateTime> candidates =
   4:         QuartersInYear(date.Year).Union(QuartersInYear(date.Year - 1));
   5:     return candidates.Where(d => d <= date).OrderBy(d => d).Last();
   6: }

Next Month End:

   1: public static DateTime NextMonthEnd(this DateTime date)
   2: {
   3:     return new DateTime(date.Year, date.Month, 1).AddMonths(2).AddDays(-1);
   4: }

Previous Month End:

   1: public static DateTime PreviousMonthEnd(this DateTime date)
   2: {
   3:     return new DateTime(date.Year, date.Month, 1).AddDays(-1);
   4: }

Hope this helps… :)
posted on Thursday, January 07, 2010 12:02 PM