[英]how to get no of days and nights between two dates using c#
i am doing a project on cab services.in this rate is different for day and night. 我正在做出租车服务项目。白天和黑夜的价格都不一样。 in the form only journey start date and end date is selected.based on this i have to calculate the no of days and nights.
在表格中,仅选择旅程的开始日期和结束日期。基于此,我必须计算日夜数。
here i am confused how to calculate the no of days and night. 在这里,我很困惑如何计算日夜数。
thanks in advance. 提前致谢。
private List<DateTime> GetDateRange(DateTime StartingDate, DateTime EndingDate)
{
if (StartingDate > EndingDate)
{
return null;
}
List<DateTime> rv = new List<DateTime>();
DateTime tmpDate = StartingDate;
do
{
rv.Add(tmpDate);
tmpDate = tmpDate.AddDays(1);
} while (tmpDate <= EndingDate);
return rv;
}
To view this code in action, copy and paste the following code into SnippetCompiler: 要查看实际运行中的代码,请将以下代码复制并粘贴到SnippetCompiler中:
DateTime StartingDate = DateTime.Parse("02/25/2007");
DateTime EndingDate = DateTime.Parse("03/06/2007");
foreach (DateTime date in GetDateRange(StartingDate,EndingDate))
{
WL(date.ToShortDateString());
}
Sample output : 样本输出:
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
Use the Subtract
method to get the difference, which is a TimeSpan
value. 使用
Subtract
获得时差,即TimeSpan
值。 Example: 例:
TimeSpan diff = SecondDate.Subtract(FirstDate);
You can get the length of the time span for example in hours: 您可以获取时间跨度的长度,例如小时数:
double hours = diff.TotalHours;
I'm not sure which time unit "days and nights" could be interpreted as, though. 我不确定哪个时间单位“昼夜”可以解释为。 Perhaps days?
也许几天?
double days = diff.TotalDays;
DateTime dt1,dt2;
//...
TimeSpan period = dt1 - dt2;
int days = period.Days;
It sounds like a very long Cab journey that takes days and nights! 听起来这是一段漫长的出租车旅程,需要花费几天和夜晚!
I think you need to define what a day and a night is more clearly in order to get your perfect answer. 我认为您需要定义一个更清晰的白天和黑夜,以获得最佳答案。 You also need to think about what impact Daylight Saving Time has on your calculations.
您还需要考虑夏时制对您的计算有何影响。
If say: 如果说:
In this case then a calculation would require you to: 在这种情况下,那么计算将需要您:
Note that: 注意:
Some pseudo code: 一些伪代码:
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.