Counting the number of specific days in a year

C

crabb

I would like to know if anyone knows how to set up an app that would
count the number of specific days in a user defined year. example,
how many Sundays, Mondays, Tuesdays, etc. in 2007 or a user defined
year, june 07 - june 08. I really don't know where to start, but we
are working on financial data and i need this for calculations.

Thanks,
Eric
 
T

Teemu Keiski

Hi,

hardcore route is just instantiate DateTime with first date and then second
datetime with the end date. Then loop while adding AddDays(1) to the loop
date until you're at the end date. In the loop then just add one to every
day "counter"

It could be something like (not tested)

DateTime startDate = new DateTime(2007,1,1);
DateTime loopDate = startDate;
DateTime endDate = new DateTime(2007, 12, 31);

int mondays = 0;

do
{
if(loopDate.DayOfWeek == DayOfWeek.Monday)
mondays += 1;

loopDate=loopDate.AddDays(1);
}
while (loopDate <= endDate);

//What does mondays variable contain at this point?
 
J

John Timney \(MVP\)

You need a little bit of brute force, but its easy enough.

Quick and dirty works well for this

DateTime fromDate = Convert.ToDateTime("1/01/2007");
DateTime toDate = Convert.ToDateTime("09/01/2007");
DateTime oNewDate;
int dayCount = toDate.Subtract(fromDate).Days;
Response.Write("Days " + dayCount + "<br>");
int i = 0;
int mon =0, tue=0, wed=0, thu=0, fri=0, sat=0, sun = 0;
while (i < dayCount){
oNewDate = fromDate.AddDays(i);
if (oNewDate.DayOfWeek == DayOfWeek.Monday) {mon += 1;}
if (oNewDate.DayOfWeek == DayOfWeek.Tuesday){ tue += 1;}
if (oNewDate.DayOfWeek == DayOfWeek.Wednesday){wed += 1;}
if (oNewDate.DayOfWeek == DayOfWeek.Thursday){thu += 1;}
if (oNewDate.DayOfWeek == DayOfWeek.Friday){fri += 1;}
if (oNewDate.DayOfWeek == DayOfWeek.Saturday){sat += 1;}
if (oNewDate.DayOfWeek == DayOfWeek.Sunday){sun += 1;}
i++;
}
Response.Write("There are " + mon.ToString() + " Mondays");
Response.Write("There are " + sun.ToString() + " Sundays");

Regards

John Timney (MVP)
http://www.johntimney.com
http://www.johntimney.com/blog
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,902
Latest member
Elena68X5

Latest Threads

Top