在日期时间增加时间,但不包括周末,并且应该在工作时间之间 [英] Add hours to datetime but exclude weekends and should be between working hours

查看:71
本文介绍了在日期时间增加时间,但不包括周末,并且应该在工作时间之间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为日期添加小时,但希望新日期不包括周末,并且只能在9.00到17.00之间.

I am trying to add hours to a date but want the new date to exclude weekends and only be between 9.00 to 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)

到目前为止,我知道了这一点,但被卡住了,因为这将不计入过去说过的日期为2012年10月2日(上周星期五)的任何日期:

so far I got this but am stuck as this will not count for any date that is in past say date passed was 10/02/2012(Friday last week) :

   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);
                }
    }

推荐答案

 static DateTime AddWithinWorkingHours(DateTime start, TimeSpan offset)
 {
    const int hoursPerDay = 8;
    const int startHour = 9;
    // Don't start counting hours until start time is during working hours
    if (start.TimeOfDay.TotalHours > startHour + hoursPerDay)
       start = start.Date.AddDays(1).AddHours(startHour);
    if (start.TimeOfDay.TotalHours < startHour)
       start = start.Date.AddHours(startHour);
    if (start.DayOfWeek == DayOfWeek.Saturday)
       start.AddDays(2);
    else if (start.DayOfWeek == DayOfWeek.Sunday)
       start.AddDays(1);
    // Calculate how much working time already passed on the first day
    TimeSpan firstDayOffset = start.TimeOfDay.Subtract(TimeSpan.FromHours(startHour));
    // Calculate number of whole days to add
    int wholeDays = (int)(offset.Add(firstDayOffset).TotalHours / hoursPerDay);
    // How many hours off the specified offset does this many whole days consume?
    TimeSpan wholeDaysHours = TimeSpan.FromHours(wholeDays * hoursPerDay);
    // Calculate the final time of day based on the number of whole days spanned and the specified offset
    TimeSpan remainder = offset - wholeDaysHours;
    // How far into the week is the starting date?
    int weekOffset = ((int)(start.DayOfWeek + 7) - (int)DayOfWeek.Monday) % 7;
    // How many weekends are spanned?
    int weekends = (int)((wholeDays + weekOffset) / 5);
    // Calculate the final result using all the above calculated values
    return start.AddDays(wholeDays + weekends * 2).Add(remainder);
 }

这篇关于在日期时间增加时间,但不包括周末,并且应该在工作时间之间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆