Run*_*CMD 2 .net c# datetime timespan winforms
假设夜间时间设定为20.30h至6.15h(AM).这两个参数是用户范围的变量.假设您的到达日期和出发日期可以从几分钟到一天以上.你如何计算夜晚的总小时数?
public static double CalculateTotalNightTimeHours(DateTime arrival,
DateTime departure,
int nightTimeStartHour,
int nightTimeStartMinute,
int nightTimeEndHour,
int nightTimeEndMinute)
{
//??
}
Run Code Online (Sandbox Code Playgroud)
编辑:我明白这可能不是直接的肯定/没有答案,但也许有人有一个优雅的解决方案来解决这个问题.回答评论:我确实想要计算用户可编辑的夜间开始和结束时间之间的总小时数(或分钟数).我正在计算访问时间,第一个日期确实是到达参数.
我的代码是:
DateTime nightStart = new DateTime( departure.Year, departure.Month, departure.Day,
nightTimeStartHour, nightTimeStartMinute, 0);
DateTime nightEnd = new DateTime( arrival.Year, arrival.Month, arrival.Day,
nightTimeEndHour, nightTimeEndMinute, 0);
if (arrival < nightEnd)
{
decimal totalHoursNight = (decimal)nightEnd.Subtract(arrival).TotalHours;
}
//...
Run Code Online (Sandbox Code Playgroud)
仅仅因为我能够应对挑战,您应该能够成功使用以下功能.请注意,这可能不是最有效的方法,但我这样做,所以我可以列出逻辑.我可能决定编辑它作为改进它的一些点,但它应该可以正常工作.
在这里注意几个假设也很重要:
考虑到这一点...
public static double Calc(DateTime start, DateTime end, int startHour, int startMin, int endHour, int endMin)
{
if (start > end)
throw new Exception();//or whatever you want to do
//create timespans for night hours
TimeSpan nightStart = new TimeSpan(startHour, startMin, 0);
TimeSpan nightEnd = new TimeSpan(endHour, endMin, 0);
//check to see if any overlapping actually happens
if (start.Date == end.Date && start.TimeOfDay >= nightEnd && end.TimeOfDay <= nightStart)
{
//no overlapping occurs so return 0
return 0;
}
//check if same day as will process this differently
if (start.Date == end.Date)
{
if (start.TimeOfDay > nightStart || end.TimeOfDay < nightEnd)
{
return (end - start).TotalHours;
}
double total = 0;
if (start.TimeOfDay < nightEnd)
{
total += (nightEnd - start.TimeOfDay).TotalHours;
}
if(end.TimeOfDay > nightStart)
{
total += (end.TimeOfDay - nightStart).TotalHours;
}
return total;
}
else//spans multiple days
{
double total = 0;
//add up first day
if (start.TimeOfDay < nightEnd)
{
total += (nightEnd - start.TimeOfDay).TotalHours;
}
if (start.TimeOfDay < nightStart)
{
total += ((new TimeSpan(24, 0, 0)) - nightStart).TotalHours;
}
else
{
total += ((new TimeSpan(24, 0, 0)) - start.TimeOfDay).TotalHours;
}
//add up the last day
if (end.TimeOfDay > nightStart)
{
total += (end.TimeOfDay - nightStart).TotalHours;
}
if (end.TimeOfDay > nightEnd)
{
total += nightEnd.TotalHours;
}
else
{
total += end.TimeOfDay.TotalHours;
}
//add up any full days
int numberOfFullDays = (end - start).Days;
if (end.TimeOfDay > start.TimeOfDay)
{
numberOfFullDays--;
}
if (numberOfFullDays > 0)
{
double hoursInFullDay = ((new TimeSpan(24, 0, 0)) - nightStart).TotalHours + nightEnd.TotalHours;
total += hoursInFullDay * numberOfFullDays;
}
return total;
}
}
Run Code Online (Sandbox Code Playgroud)
然后你可以这样称呼它:
double result = Calc(startDateTime, endDateTime, 20, 30, 6, 15);
Run Code Online (Sandbox Code Playgroud)