开发者

Get last Month of selected check boxes

开发者 https://www.devze.com 2023-01-11 11:22 出处:网络
I have a for loop that check whether some checkboxes are checked foreach (CheckBox chk in this.Controls.OfType<CheckBox>())

I have a for loop that check whether some checkboxes are checked

foreach (CheckBox chk in this.Controls.OfType<CheckBox>())
{
    if (chk.Checked)
    {
        //Some code here
    }
}

There are 12 checkboxes, 1 for each month.

What i want is to calculate the number of days between a variable StartDate and the last month. It's hard to explain sorry.

For example, StartDate = 1st September 2010, Checked Boxes are April, October and December.

The result should be the days between 01/09/2010 and 01/04/2011.

If StartDate = 1st November 2010 then the result would be the days between 01/11/2010 and 01/10/2011.

I'm think I struggling because the loop goes from jan to dec. If it was started from the startdate month I'd be OK.

Please ask some questions if 开发者_运维知识库i need to explain more.


Assuming you are olny interested in the DateTime logic, this should do:

private static TimeSpan GetLatestSpan(IEnumerable<int> monthNumbers, DateTime startDate)
{
  var candidateDates = monthNumbers
                    .Select(month => GetNearestDateInDifferentMonthWithSameDay(startDate, month));

  return candidateDates.Max() - startDate;
}

private static DateTime GetNearestDateInDifferentMonthWithSameDay(DateTime startDate, int month)
{
 return new DateTime(month > startDate.Month ? startDate.Year : startDate.Year + 1, month, startDate.Day);
}

Using your example,

var checkedMonthNumbers = new List<int>();

foreach (CheckBox chk in this.Controls.OfType<CheckBox>())
       {
         if (chk.Checked)
                {
                    checkedMonthNumbers.Add(GetMonthNumberFromCheckBox(chk));
                }
       }

MessageBox.Show("Required timespan is " + GetLatestSpan(checkedMonthNumbers, StartDate));

EDIT:

Note that I would probably rewrite the loop as:

var checkedMonthNumbers = Controls.OfType<CheckBox>()
                                  .Where(chk => ck.Checked)
                                  .Select(chk => GetMonthNumberFromCheckBox(chk));


int num=0,currentyear=2010;
for(i=startmonth;i<endmonth;i++)
{
if(i=13)
{
i=1;
currentyear++
}
num+=datetime.daysinmonth(currentyear,i);
}

i think that it will work for you


  • Search the selected months for the nearest preceding month to startDate. So basically just search only preceding months.

  • If there is none, pick the last month from the list.

0

精彩评论

暂无评论...
验证码 换一张
取 消