c# - 比较两个日期时如何使用 DateTimePicker 说明月份的变化
问题描述
我正在尝试使用 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();
}
解决方案
您有该人将待在那里的总天数。您可以将其与 AddDays 方法一起使用,以查看某一天是星期六还是星期日。例如
for ( int i = 0; i <= maxDays; i++ )
{
DateTime date = ArrivalCopy.Value.AddDays( i );
if ( date.DayOfWeek == DayOfWeek.Saturday || date.DayOfWeek == DayOfWeek.Sunday )
{
increasePriceNight++;
}
}
推荐阅读
- java - 接口如何打破类的依赖关系?
- sparql - SPARQL/DBPedia:在不知道实体页面 URI 的情况下通过属性获取实体
- c# - 在devexpress的富编辑控件中搜索一个词
- c - 将 int 转为 IEEE 754,提取指数,并将指数加 1
- python - 使用交叉验证的 kNN 算法的参数
- r - 将因子转换为整数
- javascript - 我无法将我的 div 内容完美地滚动到底部
- java - Java SDK 的 log4j2 日志记录
- android - Android上的Tensorflow,输入输出名称
- c# - C# HTMLNode 正确获取 div 的 innerText