C# 如何使用c获取两次约会之间的昼夜数
我正在做一个关于出租车服务的项目。在这个项目中,白天和晚上的费率是不同的。 在表格中,仅选择旅程开始日期和结束日期。基于此,我必须计算日夜数 在这里,我很困惑如何计算白天和黑夜的数量 提前感谢。使用减法获得差值,即时间跨度值。例如:C# 如何使用c获取两次约会之间的昼夜数,c#,.net,winforms,C#,.net,Winforms,我正在做一个关于出租车服务的项目。在这个项目中,白天和晚上的费率是不同的。 在表格中,仅选择旅程开始日期和结束日期。基于此,我必须计算日夜数 在这里,我很困惑如何计算白天和黑夜的数量 提前感谢。使用减法获得差值,即时间跨度值。例如: TimeSpan diff = SecondDate.Subtract(FirstDate); 您可以获得时间跨度的长度,例如以小时为单位: double hours = diff.TotalHours; 不过,我不确定哪种时间单位可以理解为白天和黑夜。也许几天
TimeSpan diff = SecondDate.Subtract(FirstDate);
您可以获得时间跨度的长度,例如以小时为单位:
double hours = diff.TotalHours;
不过,我不确定哪种时间单位可以理解为白天和黑夜。也许几天
double days = diff.TotalDays;
样本输出:
2/25/2007
2/26/2007
2/27/2007
2/28/2007
3/1/2007
3/2/2007
3/3/2007
3/4/2007
3/5/2007
3/6/2007
这听起来像是一个很长的出租车旅程,需要日日夜夜 我认为你需要更清楚地定义什么是白天和黑夜,才能得到完美的答案。您还需要考虑夏令时对计算的影响 如果你说: 一天是从早上6点到下午6点 剩下的时间是晚上6点到早上6点 你真的想数小时而不是数天 在这种情况下,计算需要您: 迭代从startDateTime到endDateTime的currentDateTime 选择currentDateTime中的增量,使其跳到下一个时间点(上午6点、下午6点或endDateTime) 在每个循环中,然后添加到迄今为止的numDayHours或numNightHours的累积计算中。 请注意: 您可以通过计算整个过程中的天数来加快计算速度 你需要非常小心你计算的时区,我只是希望你的出租车不要跨越时区边界! 你需要非常小心当地时间的变化-特别是夏令时类型的变化-从下午6点到早上6点的持续时间并不总是12小时! 一些伪代码:
var numDayHours = 0.0;
var numNightHours = 0.0;
var current = startDateTime;
while (current < endDateTime)
{
next_hop = calculate_next_hop (current, endDateTime);
// select next date time
switch (next_hop.hop_type)
{
case HopType.night_time_hop:
numNightHours += next_hop.num_hours;
break;
case HopType.day_time_hop:
numDayHours += next_hop.num_hours;
break;
}
current = next_hop.EndDateTime;
}
// and here is the result
double numDays = numDayHours / 12.0;
double numHours = numNightHours / 12.0;
为什么WL在这里以红色突出显示?
DateTime StartingDate = DateTime.Parse("02/25/2007");
DateTime EndingDate = DateTime.Parse("03/06/2007");
foreach (DateTime date in GetDateRange(StartingDate,EndingDate))
{
WL(date.ToShortDateString());
}
2/25/2007
2/26/2007
2/27/2007
2/28/2007
3/1/2007
3/2/2007
3/3/2007
3/4/2007
3/5/2007
3/6/2007
var numDayHours = 0.0;
var numNightHours = 0.0;
var current = startDateTime;
while (current < endDateTime)
{
next_hop = calculate_next_hop (current, endDateTime);
// select next date time
switch (next_hop.hop_type)
{
case HopType.night_time_hop:
numNightHours += next_hop.num_hours;
break;
case HopType.day_time_hop:
numDayHours += next_hop.num_hours;
break;
}
current = next_hop.EndDateTime;
}
// and here is the result
double numDays = numDayHours / 12.0;
double numHours = numNightHours / 12.0;