如何将整数值添加到日期并在 C# 中计算结束日期

how to add an integer value to a date and calculate the end date in c#

我正在构建一个 C# 控制台应用程序。

假设用户输入为

如何在排除周末和public假期后显示任务的结束日期。

我已经通过考虑所有可能的验证来实现用户输入。

static void Main(string[] args)
{
    //effort hours
    Console.Write("Enter No of hours: ");
    int hours;
    if (Int32.TryParse(Console.ReadLine(), out hours))
    {
        if (hours <= 0)
        {
            Console.WriteLine("Hours of effort cannot be a negative value or 0");
        }
        else
        {
            Console.WriteLine("The no of hours entered is: " + hours);
        }
    }
    else
    {
        Console.WriteLine("You have entered an incorrect value.");
    }
    Console.ReadLine();

    //working hours per day
    Console.Write("Enter No of working hours per day: ");
    int WorkingHours;
    if (Int32.TryParse(Console.ReadLine(), out WorkingHours))
    {
        if (WorkingHours <= 0 || WorkingHours > 9)
        {
            Console.WriteLine("Maximum working hours per day is 9 hours and no of hours entered cannot be 0 or negative");
        }
        else
        {
            Console.WriteLine("The no of working hours entered is: " + WorkingHours);
        }
    }
    else
    {
        Console.WriteLine("You have entered an incorrect value.");
    }
    Console.ReadLine();

    //Enter start date
    Console.WriteLine("Enter the start date date (e.g. dd/mm/yyyy): ");
    DateTime startDate;
    {
        while (!DateTime.TryParse(Console.ReadLine(), out startDate))
        {
            Console.WriteLine("You have entered an incorrect value.");
            Console.WriteLine("Enter the start date date (e.g. dd/mm/yyyy): ");
        }
        Console.WriteLine("The startdate is: " + startDate);
    }
}

如评论中所述,您需要提供世界各地不同的假期列表。此外,定义的“工作日”/“周末”也可能因您正在开发应用程序的地区而异。例如,一些中东国家在 Thursday/Friday.

放周末

假设您有规律的 Saturday/Sunday 周末,您可以修改 FluentDateTime 提供的 DateTime Extension 如下,以包含假期集合

public static class Extentions
{

    public static DateTime AddBusinessDays(this DateTime current, int days,IEnumerable<DateTime> holidayList)
    {
        var sign = Math.Sign(days);
        var unsignedDays = Math.Abs(days);
        var holidayCollection = new HashSet<DateTime>(holidayList);
        for (var i = 0; i < unsignedDays; i++)
        {
            do
            {
                current = current.AddDays(sign);
            } while (current.DayOfWeek == DayOfWeek.Saturday 
                   || current.DayOfWeek == DayOfWeek.Sunday 
                   || holidayCollection.Contains(current));
        }
        return current;
    }
}

您现在可以将方法用作

startDate.AddBusinessDays(totalHours/perDayHours,holidayList)

如果如前所述,您需要考虑不同的周末,您需要对上面的代码进行适当的更改。

PS:以上代码假定您只对“结束日期”感兴趣,而不对准确的时间感兴趣。

不用循环解决这个问题最简单的方法是这样的:

static void Main ( string[] args ) {

    BeginRoutine:
        //effort hours
        Console.Write( "Enter No of hours: " );
        int hours;
        if ( Int32.TryParse( Console.ReadLine(), out hours ) ) {
            if ( hours <= 0 ) {
                Console.WriteLine( "Hours of effort cannot be a negative value or 0" );
            }
            else {
                Console.WriteLine( "The no of hours entered is: " + hours );
            }
        }
        else {
            Console.WriteLine( "You have entered an incorrect value." );
        }
        //Console.ReadLine();

        //working hours per day
        Console.Write( "Enter No of working hours per day: " );
        int WorkingHours;
        if ( Int32.TryParse( Console.ReadLine(), out WorkingHours ) ) {
            if ( WorkingHours <= 0 || WorkingHours > 9 ) {
                Console.WriteLine( "Maximum working hours per day is 9 hours and no of hours entered cannot be 0 or negative" );
            }
            else {
                Console.WriteLine( "The no of working hours entered is: " + WorkingHours );
            }
        }
        else {
            Console.WriteLine( "You have entered an incorrect value." );
        }
        //Console.ReadLine();
    
    GetStartDate:
        //Enter start date
        Console.WriteLine( "Enter the start date date (e.g. dd/mm/yyyy): " );

        DateTime startDate;
        while ( !DateTime.TryParse( Console.ReadLine(), out startDate ) ) {
            Console.WriteLine( "You have entered an incorrect value." );
            Console.WriteLine( "Enter the start date date (e.g. dd/mm/yyyy): " );
        }

        // Make sure the start date isn't a Saturday or Sunday!
        if ( startDate.DayOfWeek == DayOfWeek.Saturday || startDate.DayOfWeek == DayOfWeek.Sunday ) {
            Console.WriteLine( "Cannot start work on {0} because it is a {1}",
                startDate.ToString( "MM/dd/yyyy" ), startDate.DayOfWeek );

            goto GetStartDate;
        }
        Console.WriteLine( "The startdate is: " + startDate );
        
        // Determine number of work days:
        double workDays = hours / WorkingHours;
        Console.WriteLine( "\nTask will take {0} work days", workDays.ToString("0.00") );

        // Determine total weeks and days:
        double totalWeeks = workDays / 5D;
        double totalDays = ( totalWeeks * 7D );

        // Print statistics to Console for user
        Console.WriteLine( "Task will take {0} weeks and {1} total calender days ...", 
            totalWeeks.ToString( "0.00" ), totalDays.ToString( "0.00" ) );

        // Calculate ending date and display it:
        DateTime endDate = startDate.AddDays(totalDays);
        Console.WriteLine( "The ending date will be {0}", endDate.ToString( "MM/dd/yyyy" ) );
        
        // Prompt user to restart:
        Console.WriteLine( "\n\nProgram complete ... press Y to restart or any other key to continue.\n" );
        if ( Console.ReadKey( true ).Key == ConsoleKey.Y ) goto BeginRoutine;
    }

我还没有针对所有可能的情况详尽地测试这个例程,它肯定不是做到这一点的“最佳”方式(例如,它没有考虑像圣诞节这样的假期,也没有针对地区和地区进行本地化)文化),但它似乎可以快速高效地解决您的简单问题。奇怪的是,我刚刚为我的策略游戏原型编写了一些非常有趣的 DateTime 代码,我在其中使用游戏循环来驱动 DateTime 前进并创建游戏内时间系统。

编辑:请注意,我几乎完好无损地保留了您的原始代码,只是在其下方添加了...解决假期的一种简单方法是创建包含假期的日期列表,查看开始之间是否有任何日期日期和结束日期(可能使用自定义查询)并为每个日期添加一天。