获取时间段内的工作日时间(除去周末)

   ///


        /// Get business day which exclude weekend
        ///

        ///
        ///
        ///
        public string GetWorkDayCount(DateTime beginDay, DateTime endDay)
        {
            //set creat day and end day as business day.
            if (beginDay.DayOfWeek == DayOfWeek.Saturday)
                beginDay = beginDay.AddDays(2);
            if (beginDay.DayOfWeek == DayOfWeek.Sunday)
                beginDay = beginDay.AddDays(1);
            if (endDay.DayOfWeek == DayOfWeek.Saturday)
                endDay = endDay.AddDays(2);
            if (endDay.DayOfWeek == DayOfWeek.Sunday)
                endDay = endDay.AddDays(1);

            //get days between create day and end day
            var allDays = Convert.ToDecimal(ExecDateDiff(beginDay, endDay, 1)) + 1;

            //get weekend days between create day and end day
            var weekendDays = Convert.ToDecimal(ExecDateDiff(GetFirstDayOfWeek(beginDay), GetFirstDayOfWeek(endDay), 1)) / 7 * 2;

            //get work day
            var workDay = allDays - weekendDays;

            return workDay.ToString();
        }

        ///
        /// Calculate the time span
        ///

        ///
        ///
        ///
        public string ExecDateDiff(DateTime dateBegin, DateTime dateEnd, int timeType)
        {
            TimeSpan ts1 = new TimeSpan(dateBegin.Ticks);
            TimeSpan ts2 = new TimeSpan(dateEnd.Ticks);
            TimeSpan ts3 = ts1.Subtract(ts2).Duration();
            string result = string.Empty;
            switch (timeType)
            {
                case 1:
                    result = ts3.TotalDays.ToString();
                    break;
                case 2:
                    result = ts3.TotalHours.ToString();
                    break;
                case 3:
                    result = ts3.TotalMinutes.ToString();
                    break;
                case 4:
                    result = ts3.TotalSeconds.ToString();
                    break;
            }
            return result;
        }

        ///
        /// Get first day of the week
        ///

        ///
        ///
        public DateTime GetFirstDayOfWeek(DateTime time)
        {
            int i = time.DayOfWeek - DayOfWeek.Monday;
            if (i == -1) i = 6;
            TimeSpan ts = new TimeSpan(i, 0, 0, 0);
            return time.Subtract(ts);
        }

转载于:https://www.cnblogs.com/cnqct/p/8571940.html

你可能感兴趣的:(获取时间段内的工作日时间(除去周末))