我正试图使用windows窗体和C#创建一个基本的酒店房间预订应用程序。我最初是通过创建for循环开始的,理由是到达日期总是小于离开日期。这一切都如预期的那样工作,直到我试着为6月30日预订一个房间,并在7月1日离开。从下面的代码可以看出,它永远不会进入for-loop,因为到达日期不<比出发日期小。我创建了一个maxDays int,其中包含了这个人将要停留的最大天数,并将其作为循环的锚。这可能归结为大部分逻辑问题和一些愚蠢的错误,因为我在代码中几乎没有使用日期的经验。任何关于这个问题的建议都将是巨大的。
private void CalculateButton_Click(object sender, EventArgs e)
{
//Prints out number of nights at hotel.
NumberOfNightsTextbox.Text = (DepartureDatePicker.Value.Day - ArrivalDatePicker.Value.Day).ToString("d");
//Creates a copy of the current Arrival and Departure date.
DateTimePicker ArrivalCopy = ArrivalDatePicker;
DateTimePicker DepartureCopy = DepartureDatePicker;
//Creates an int to store the current Arrival and Departure Month.
int arrivalMonth = ArrivalDatePicker.Value.Month;
int departureMonth = DepartureDatePicker.Value.Month;
//Creates a int that is used to determine how many loops the For statement should loop for.
//May need to add the monthly days after doing a check.
int maxDays = DepartureDatePicker.Value.Day;
//Gets the difference of the Arrival and Departure and converts it to an Int.
double differnceD = (DepartureDatePicker.Value - ArrivalDatePicker.Value).TotalDays;
int diff = (int)Math.Round(differnceD);
if (arrivalMonth < departureMonth)
{
if (departureMonth == 1 || departureMonth == 3 ||
departureMonth == 5 || departureMonth == 7 ||
departureMonth == 8 || departureMonth == 10 ||
departureMonth == 11)
{
diff += 31;
}
else if (departureMonth == 2)
{
diff += 28;
}
else if (departureMonth == 4 || departureMonth == 6 || departureMonth == 9 || departureMonth == 11)
{
diff += 30;
}
}
if (arrivalMonth == departureMonth)
{
for (int i = ArrivalDatePicker.Value.Day; i < maxDays + 1; i++)
{
if (ArrivalCopy.Value.DayOfWeek == DayOfWeek.Saturday || ArrivalCopy.Value.DayOfWeek == DayOfWeek.Sunday)
{
increasePriceNight++;
}
ArrivalCopy.Value = ArrivalCopy.Value.AddDays(1);
}
}
TotalPriceTextbox.Text = (((diff - increasePriceNight) * 120) + (increasePriceNight * 150)).ToString("C");
AvgPricePerNightTextbox.Text = ((((diff - increasePriceNight) * 120) + (increasePriceNight * 150)) / diff).ToString();
}
你有总的天数,该人将留在那里。你可以使用AddDays方法来查看某一天是周六还是周日。例如
for ( int i = 0; i <= maxDays; i++ )
{
DateTime date = ArrivalCopy.Value.AddDays( i );
if ( date.DayOfWeek == DayOfWeek.Saturday || date.DayOfWeek == DayOfWeek.Sunday )
{
increasePriceNight++;
}
}
我不知道你为什么决定用这种逻辑。你可以做得更简单
double days = (DepartureDatePicker.Value - ArrivalDatePicker.Value).TotalDays;
int daysTotal = Convert.ToInt32(Math.Ceiling(days));
基本上,如果原 days
是类似0.2或1.3的东西,你只需将其四舍五入到下一个整数。这就是人必须支付的天数。
现在,有了天数,你可以迭代你的 dates
每次重复增加一天,并检查是哪一天,并收取适当的费用 - 折扣或加价
DateTeime startDate = ArrivalDatePicker.Value.Date;
decimal totalPrice = 0;
for (int dayNo = 0; dayNo < daysTotal; dayNo++)
{
DateTime currDate = startDate.AddDays(dayNo);
totalPrice += GetPriceForDate(currDate);
}
在 GetPriceForDate
你调查一下日期。周几、月几号等,并根据业务规则进行定价。