How to get first and last fridays in a month?

  • Thread starter Thread starter Sasidhar Parvatham
  • Start date Start date
S

Sasidhar Parvatham

Hello All,

Is there a way I can get dates for first and last fridays of a month? Any
suggestion would be helpful.

Thanks.
 
There's no direct way that I'm aware of, but you could write a simple piece
of code like this:

DateTime dtFirstFriday = DateTime.MinValue;
DateTime dtLastFriday = DateTime.MaxValue;

DateTime dtFront = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
DateTime dtBack = new DateTime(DateTime.Now.Year, DateTime.Now.Month,
DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month));

while (dtFirstFriday == DateTime.MinValue || dtLastFriday ==
DateTime.MaxValue)
{
if (dtFirstFriday == DateTime.MinValue && dtFront.DayOfWeek ==
DayOfWeek.Friday)
dtFirstFriday = dtFront;
else
dtFront = dtFront.AddDays(1.0);

if (dtLastFriday == DateTime.MaxValue && dtBack.DayOfWeek ==
DayOfWeek.Friday)
dtLastFriday = dtBack;
else
dtBack= dtBack.AddDays(-1.0);
}

At the end of the loop dtFirstFriday and dtLastFriday will hold the
appropriate values.

--
Kai Brinkmann [Microsoft]

Please do not send e-mail directly to this alias. This alias is for
newsgroup purposes only.
This posting is provided "AS IS" with no warranties, and confers no rights.
 
Try this:

private void FirstAndLastFridays(int month, int year, out int first, out int
last)
{
//get last friday
int lastFriday = DateTime.DaysInMonth(year, month);
DateTime day = new DateTime(year, month, lastFriday);
do
{
day = new DateTime(year, month, lastFriday);
if (day.DayOfWeek != DayOfWeek.Friday)
lastFriday--;
}
while (day.DayOfWeek != DayOfWeek.Friday);
//get first friday
int firstFriday = 1;
do
{
day = new DateTime(year, month, firstFriday);
if (day.DayOfWeek != DayOfWeek.Friday)
firstFriday++;
}
while (day.DayOfWeek != DayOfWeek.Friday);
first = firstFriday;
last = lastFriday;
}
 
Back
Top