Get first Sun last Sat

  • Thread starter Thread starter David C
  • Start date Start date
D

David C

I am looking for a routine that would give me the first Sunday in a month
and the last Saturday in a month for any given date. For example, Passing
10/20/2009 would return 9/27/2009 for the first Sunday and 10/31/2009 for
the last Saturday in the month. I can get the first and last day of a month
but this one I cannot figure out. I am using asp.net and framework 3.5
Thanks.

David
 
David said:
I am looking for a routine that would give me the first Sunday in a month
and the last Saturday in a month for any given date. For example, Passing
10/20/2009 would return 9/27/2009 for the first Sunday and 10/31/2009 for
the last Saturday in the month. I can get the first and last day of a month
but this one I cannot figure out. I am using asp.net and framework 3.5
Thanks.

David

Maybe, this will help you.

<http://msdn.microsoft.com/en-us/lib...fo.transitiontime.createfloatingdaterule.aspx>
 
Mark Rae said:
DateTime FirstSundayInMonth(DateTime pdtmStart)
{
DateTime dtmFirstSundayInMonth = new DateTime(pdtmStart.Year,
pdtmStart.Month, 1);
while (dtmFirstSundayInMonth.DayOfWeek != DayOfWeek.Sunday)
{
dtmFirstSundayInMonth = dtmFirstSundayInMonth.AddDays(1);
}
return dtmFirstSundayInMonth;
}

DateTime LastSaturdayInMonth(DateTime pdtmStart)
{
DateTime dtmLastSaturdayInMonth = new DateTime(pdtmStart.Year,
pdtmStart.Month, 1).AddMonths(1).AddDays(-1);
while (dtmLastSaturdayInMonth.DayOfWeek != DayOfWeek.Saturday)
{
dtmLastSaturdayInMonth = dtmLastSaturdayInMonth.AddDays(-1);
}
return dtmLastSaturdayInMonth;
}



As far as I'm concerned, the first Sunday in October 2009 is 4th.

If you consider 27th September 2009 to be the first Sunday in October
2009, you'll need to modify the above to accommodate whatever non-standard
calendar you're using...

I was looking at the first Sunday on a calendar as I need to identify the
Sunday - Saturday that includes ANY day in the month. Look at the calendar
and you will see what I mean. Thanks.

David
 
its simple arithmetic:

for DateTime d

// get first day of month
var fom = d.AddDays(-d.Day + 1);

// get last day of month
var lom = d.AddDays(-d.Day + 1).AddMonths(1).AddDays(-1);

// get the first sunday
var firstSun = fom.AddDays(-((int)fom.DayOfWeek) % 7);

// get last saturday
var lastSat = lom.AddDays(7 - ((int)lom.DayOfWeek + 1) % 7);

-- bruce (sqlwork.com)
 
Back
Top