c# - 将时间添加到日期时间,但排除周末,并且应该在工作时间之间

标签 c# datetime weekend

我尝试在日期中添加小时数,但希望新日期排除周末,并且仅在 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/

相关文章:

ios - 使用日期/时间和核心图始终在原点显示标签

c# - array.Max();对于数组索引而不是值

c# - 如何在目标阈值内简化图像停止运动

MySQL 日期时间插入问题。奇怪的错误?

删除数据框中的周末数据

python - Pandas :删除等于周末的列

jquery - 从日期字段(mm/dd/yyyy)中减去天数,不包括周末jquery

c# - 在异步方法中使用时 SignalR 调用不返回

c# - 如何编写参数化的oracle插入查询?

php - 在 php 和 mySQL 中将 DATE 转换为 DATETIME