We help IT Professionals succeed at work.

# c# date calculation bug

on
Medium Priority
333 Views
hi all, have a bug in my code regarding calculating current end of week.  problem is when the month changes, my end week date gets corrupted.

private DateTime weekenddate = DateTime.Today.AddDays(-(int)(DateTime.Today.DayOfWeek) + 6);

*** weekenddate ok here, shows 4/1/06

later in code, to get last day of week:

int day = DateTime.Today.Day;
int month = DateTime.Today.Month;
int year = DateTime.Today.Year;

switch (TimeFrame.SelectedValue)
{
case "Week":
startdate = new DateTime(year, month, weekstartdate.Day, 0, 0, 0);
**                enddate = new DateTime(year, month, weekenddate.Day, 23, 59, 59, 997);  **

**** but here enddate year is showing 2006, month 3, weekenddate=4/1/06 (correct) .Day = 1 (correct), 23, 59, 59, 997)

how can i correctly calculate weekend date when month changes, as it has with this week.  my week is considered sunday midnight to saturday 11:59:59:997.

Comment
Watch Question

## View Solution Only

Commented:
I tried this and it worked. Is this what you're looking for?

DateTime today = DateTime.Today;
DateTime weekStart = today.AddDays( - ((int)today.DayOfWeek) );

Console.WriteLine("Start: {0:R}", weekStart);
Console.WriteLine("End:   {0:R}", weekEnd);

-------

OUTPUT:

Start: Sun, 26 Mar 2006 00:00:00 GMT
End:   Sat, 01 Apr 2006 23:59:59 GMT

Commented:
no, the weekend datetime is fine when declared, it's when i'm in the switch statement determining the actual date for weekend date that the month change corrupts the field.

enddate = new DateTime(year, month, weekenddate.Day, 23, 59, 59, 997);  **

year = 2006, month = 3 -- wrong, needs to be 4 since the month changed at the end of the week
Commented:
Well, Month is wrong because, above, you're declaring 'month' as DateTime.Today.Month. I'm not sure why you're doing all that work again in the switch, since you had it, essentially, write up at the top.

========= C# EXAMPLE =========

DateTime today = DateTime.Today;

switch (TimeFrame.SelectedValue)
{
case "Week":

startdate = today.AddDays( - ((int)today.DayOfWeek) );
break;
...

Not the solution you were looking for? Getting a personalized solution is easy.

##### Thanks for using Experts Exchange.

• View three pieces of content (articles, solutions, posts, and videos)
• Ask the experts questions (counted toward content limit)
• Customize your dashboard and profile