Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 316
  • Last Modified:

c# date calculation bug

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 weekstartdate = DateTime.Today.AddDays(-(int)(DateTime.Today.DayOfWeek));
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.

thanks in advanced
0
aaalife
Asked:
aaalife
  • 2
1 Solution
 
c_myersCommented:
I tried this and it worked. Is this what you're looking for?

DateTime today = DateTime.Today;
DateTime weekStart = today.AddDays( - ((int)today.DayOfWeek) );
DateTime weekEnd = weekStart.AddDays(7).AddMilliseconds(-3);
            
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

0
 
aaalifeAuthor 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
0
 
c_myersCommented:
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.

Try this instead:

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

DateTime today = DateTime.Today;

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

        startdate = today.AddDays( - ((int)today.DayOfWeek) );
        endDate = startdate.AddDays(7).AddMilliseconds(-3);
        break;
...
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now