I have a DateTime object wich contains the current date, now I want C# to determine how long the week will last (mon - fri). I've been trying several things, but nothing seems to work.
For example, if the current date would be 12/04/2009, and it would be a monday, it should return 4 (there are four days left to friday, friday included).
Sorry for any spelling mistakes, I normally speak duch...
Loading
MaartenPosted Dec 21, 2007, 4:56 AM
AlanPosted Dec 20, 2007, 7:00 PM
I was just playing around some more with this and I found that this simpler (though more cryptic) version also works:
using System;
class Program
{
static void Main()
{
DateTime dt = new DateTime(2007, 12, 17);
int rest = RestOfWeek(dt);
Console.WriteLine(rest); // 4
Console.ReadLine();
}
static int RestOfWeek(DateTime dt)
{
int rest = 5 - (int)dt.DayOfWeek;
if (rest == -1) rest = 5;
return rest;
}
}
The reason it works is because in the DayOfWeek enum, Sunday has a a value of 0, Monday a value of 1 and so on up to 6 for Saturday.
AlanPosted Dec 20, 2007, 6:45 PM
This should work OK:
using System;
class Program
{
static void Main()
{
DateTime dt = new DateTime(2007, 12, 17);
int rest = RestOfWeek(dt);
Console.WriteLine(rest); // 4
Console.ReadLine();
}
static int RestOfWeek(DateTime dt)
{
switch (dt.DayOfWeek)
{
case DayOfWeek.Saturday:
case DayOfWeek.Sunday:
return 5;
case DayOfWeek.Monday:
return 4;
case DayOfWeek.Tuesday:
return 3;
case DayOfWeek.Wednesday:
return 2;
case DayOfWeek.Thursday:
return 1;
default:
return 0;
}
}
}
Incidentally, according to my calendar, 12 April 2009 is a Sunday and 4 December 2009 is a Friday. So, I've done the example on a date we can both agree was a Monday, 17 December 2007 :)