我有两个文本框,用于选择From和a To日期。我需要一个循环,其中外循环将持续一年,内循环将运行每个月。
问题在于下面的代码,如果我选择11/01/2011和06/30/2012,我的月份循环会在第11个月运行一次。之后循环退出..感谢任何帮助。
我正在使用下面的代码查看SharePoint日历列表(使用CAML查询)并获取连续3天,5天连续几天某个房间可用,不包括周末。想法是使用CAML查询来获取每个月的免费天数,并一直重复到最后一个月。
int year = 0, month = 0;
for (year = Calendar1.SelectedDate.Year; year <= Calendar2.SelectedDate.Year; year++)
{
int i = year;
for (month = Calendar1.SelectedDate.Month; month <= Calendar2.SelectedDate.Month; month++)
{
int j = month;
}
}
答案 0 :(得分:5)
这样的事情会起作用吗?
for (DateTime date = Calendar1.SelectedDate; date < Calendar2.SelectedDate; date = date.AddMonths(1))
{
//code
}
答案 1 :(得分:4)
如果我理解正确,您希望在两个日期之间迭代每个月。如果是这样,这应该有效:
var dt2 = Calendar2.SelectedDate.Year;
var current = Calendar1.SelectedDate;
while (current < dt2)
{
current = current.AddMonths(1);
//do your work for each month here
}
答案 2 :(得分:1)
内循环的起始和结束编号应该是有条件的。
如果你在开始年份,那么开始月份应该是选定的月份;否则它应该是1.
如果您在结束年份,那么结束月份应该是选定的月份;否则它应该是12。
示例:
var startYear = Calendar1.SelectedDate.Year;
var endYear = Calender2.SelectedDate.Year;
var startMonth = Calender1.SelectedDate.Month;
var endMonth = Calender2.SelectedDate.Month;
for (var year = startYear; year <= endYear; year++)
{
var sm = year == startYear ? startMonth : 1;
var em = year == endYear ? endMonth : 12;
for (var month = sm; month <= em; month++)
{
}
}
答案 3 :(得分:0)
对于开始年份,您需要从适当的月份开始内循环,并运行所有12个月,除非在结束年份,您应该运行到适当的月份。这样的事情应该有效:
int year = 0, month = 0;
for (year = Calendar1.SelectedDate.Year; year <= Calendar2.SelectedDate.Year; year++)
{
int i = year;
for (month = (i==Calendar1.SelectedDate.Year ? Calendar1.SelectedDate.Month : 1); month <= (i==Calendar2.SelectedDate.Year ? Calendar2.SelectedDate.Month : 12); month++)
{
int j = month;
}
}
答案 4 :(得分:0)
//Function return First day in Month For Date --example : 01-09-2012
public static DateTime FirstDayOfMonthFromDateTime(DateTime dateTime)
{
return new DateTime(dateTime.Year, dateTime.Month, 1);
}
//code used to loop throw a Date range for each month
DateTime FirstDayInMonth = FirstDayOfMonthFromDateTime(Date);
DateTime TempDay = FirstDayInMonth;
int days = DateTime.DaysInMonth(FirstDayInMonth.Year, FirstDayInMonth.Month);
for (int i = 0; i < days; i++)
{
System.Out.Println(TempDay.toString());
TempDay.AddDays(1);
}
//then used code for each month in year (simple loop from 1-12)..