我尝试在日期中添加小时数,但希望新日期排除周末,并且仅在 9:00 到 17:00 之间。
示例:
第一个场景:
if my date is 23/02/2012 16:00:00.
if I add 4 hours to that my new date should be 24/02/2012 12:00:00 (which will be within working hours)
第二种情况:
if my date is 24/02/2012 09:00:00 (which is a friday)
if I add 24 hours then the new date should be 27/02/2012 09:00:00 (which would be monday next week at 9am)
到目前为止,我得到了这个,但被卡住了,因为这不会计算过去的任何日期,比如过去的日期是 10/02/2012(上周星期五):
private static void ExcludeWeekend(Datetime dt)
{
DateTime todaysDate = DateTime.Today;
DateTime dueDate = null;
if (dueDate.DayOfWeek == DayOfWeek.Friday)
{
dueDate.AddHours(48);
}
else if (dueDate.DayOfWeek == DayOfWeek.Saturday)
{
dueDate.AddHours(72);
}
}
最佳答案
您可以使用Time Period Library for .NET中的类CalendarDateAdd :
// ----------------------------------------------------------------------
public void CalendarDateAddSample()
{
CalendarDateAdd calendarDateAdd = new CalendarDateAdd();
// use only weekdays
calendarDateAdd.AddWorkingWeekDays();
// setup working hours
calendarDateAdd.WorkingHours.Add( new HourRange( new Time( 09 ), new Time( 17 ) ) );
DateTime start = new DateTime( 2012, 2, 23 ); // start date
TimeSpan offset = new TimeSpan( 4, 0, 0 ); // 4 hours
DateTime? end = calendarDateAdd.Add( start, offset ); // end date
Console.WriteLine( "start: {0}", start );
Console.WriteLine( "offset: {0}", offset );
Console.WriteLine( "end: {0}", end );
} // CalendarDateAddSample
关于c# - 将时间添加到日期时间,但排除周末,并且应该在工作时间之间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9413984/