Click here to Skip to main content
15,884,298 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hi,
The following c# code tells you if the date is the last day of the month.
Question:
How can I get the last WORKING day of the month?
for example, for march, th elast day is saturday which is 31st. But I want the code to return 30th which is the last working day of march.
Thanks

C#
private bool IsLastDayOfMonth(DateTime dtDate)
        {
            DateTime dtTo = dtDate.Date;
            dtTo = dtTo.AddMonths(1);
            // remove all of the days in the next month 
            // to get bumped down to the last day of the 
            // previous month 
            dtTo = dtTo.AddDays(-(dtTo.Day));

            if (dtDate.Date == dtTo)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
Posted
Comments
arkiboys 28-Mar-12 5:08am    
Thank you

1 solution

Try this:
C#
// ----------------------------------------------------------------------
private static DateTime LastDayOfMonth( int year, int month )
{
  return new DateTime( year, month, DateTimeFormatInfo.CurrentInfo.Calendar.GetDaysInMonth( year, month ) );
} // LastDayOfMonth

// ----------------------------------------------------------------------
private static bool IsLastDayOfMonth( DateTime test )
{
  DateTime lastDayOfMonth = LastDayOfMonth( test.Year, test.Month );
  return test.Day == lastDayOfMonth.Day;
} // IsLastDayOfMonth

// ----------------------------------------------------------------------
private static bool IsLastWorkingDayOfMonth( DateTime test )
{
  DateTime lastWorkingDayOfMonth = LastDayOfMonth( test.Year, test.Month );
  while ( lastWorkingDayOfMonth.DayOfWeek == DayOfWeek.Saturday || 
    lastWorkingDayOfMonth.DayOfWeek == DayOfWeek.Sunday )
  {
    lastWorkingDayOfMonth = lastWorkingDayOfMonth.AddDays( -1 );
  }

  return test.Day == lastWorkingDayOfMonth.Day;
} // IsLastWorkingDayOfMonth
 
Share this answer
 
Comments
pietvredeveld 28-Mar-12 6:06am    
Nice solution. But keep in mind that in many regions in the world Saturday and Sunday are working days.
To solve that there must be a definition of working days (or non working days) been added and tested against that definition.
Jani Giannoudis 28-Mar-12 7:45am    
That's true. A customizable solution would be a List<DayOfWeek> as implemented in the class CalendarDateAdd of the http://www.codeproject.com/Articles/168662/Time-Period-Library-for-NET.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900