我正在尝试使用Windows窗体和C#创建一个基本的酒店客房预订应用程序。最初,我基于创建for循环开始,理由是到达日期始终小于出发日期。这一切都按预期进行,直到我尝试预订6月30日的房间并于7月1日离开。从下面的代码中可以看到,它永远不会进入for循环,因为到达日期不小于出发日期。我创建了一个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();
}
答案 0 :(得分:0)
您拥有该人待在那里的总天数。您可以将其与AddDays方法一起使用,以查看一天是星期六还是星期日。例如
for ( int i = 0; i <= maxDays; i++ )
{
DateTime date = ArrivalCopy.Value.AddDays( i );
if ( date.DayOfWeek == DayOfWeek.Saturday || date.DayOfWeek == DayOfWeek.Sunday )
{
increasePriceNight++;
}
}
答案 1 :(得分:0)
我不知道您为什么决定采用这种逻辑。您可以轻松得多
double days = (DepartureDatePicker.Value - ArrivalDatePicker.Value).TotalDays;
int daysTotal = Convert.ToInt32(Math.Ceiling(days));
基本上,如果原始的days
类似于0.2或1.3,则将其舍入到下一个整数。这是一个人必须支付的天数。
现在,有几天的时间,您可以迭代dates
,并在每次迭代中添加1天,并检查它是一周中的哪一天,并收取适当的费用-折扣或附加费
DateTeime startDate = ArrivalDatePicker.Value.Date;
decimal totalPrice = 0;
for (int dayNo = 0; dayNo < daysTotal; dayNo++)
{
DateTime currDate = startDate.AddDays(dayNo);
totalPrice += GetPriceForDate(currDate);
}
您在GetPriceForDate
中调查日期。每周的星期几,每月的哪一天等,并根据业务规则进行定价。