Hi,
I am creating a calender type application, so I need some help with some date functions.
1. Given a year and month, I need to list the day name and number.
So for example, I'll initialize a DateTime object:
Year 2008
Month: 8 (August)
Now I want to enumerate through all the days (with the correct # of days obviously), and output the name of the day along with the number of the day.
Output:
1 Friday
2 Saturday
3 Sunday
.
.
.
31 Monday
2. Given a date range, how many days are between them?
So say I want to know the number of days in the date range August 1 2008 to Dec 15 2008
P.S Do these built in functions take leap years etc. into consideration?

1 answers
The first part can be done with the following code:
using System;
class Program
{
static void Main(string[] args)
{
if (args.Length != 2)
{
Console.WriteLine("There must be exactly 2 arguments");
return;
}
int month, year;
bool isValid;
isValid = int.TryParse(args[0], out year);
if (!isValid || year < 2000 || year > 2020)
{
Console.WriteLine("Invalid year");
return;
}
isValid = int.TryParse(args[1], out month);
if (!isValid || month < 1|| month > 12)
{
Console.WriteLine("Invalid month");
return;
}
DateTime dt = new DateTime(year, month, 1);
Console.Clear();
Console.WriteLine("Days of week for {0}\n", dt.ToString("MMMM, yyyy"));
int numDays = DateTime.DaysInMonth(year, month);
for (int i = 1; i <= numDays; i++)
{
if (i > 1) dt = dt.AddDays(1);
Console.WriteLine("{0,2} {1}", i, dt.DayOfWeek);
}
Console.ReadLine();
}
}
As you'll see, the program accepts its arguments from the command line. So, if the program were called dnp.exe, you'd enter at the command line: dnp 2008 8 to see the results for August this year.
The second part can be done with code such as this:
DateTime dt1 = DateTime.Parse("August 1 2008");
DateTime dt2 = DateTime.Parse("August 2 2008");
TimeSpan ts = dt2 - dt1;
Console.WriteLine("The number of days between {0} and {1} is {2}", dt1.ToShortDateString(), dt2.ToShortDateString(), ts.Days);
Yes, the relevant DateTime struct methods/properties do take leap years into account.
answered 2 years ago by:
17279
Incidentally, the second bit of code works out the span between 2 dates i.e. 1 in the example. To get the total number of days, inclusive, between two dates just add 1.
answered 2 years ago by:
17279
This post was imported from csharpfriends, if you have a similiar question please ask it again.
All previous members have been migrated, hope you enjoy the new platform!