【问题标题】:c# windows form Application for employee management [closed]c# windows form应用程序进行员工管理[关闭]
【发布时间】:2018-11-04 18:24:57
【问题描述】:

在基于 C# windows 窗体的应用程序中。我使用了两个日期时间选择器,一个用于 From,另一个用于 To。

如果员工在 dateTime picker1 中选择 5 月 30 日休假,在 datetime picker2 中选择 6 月 2 日,则休假 4 天。

我的问题是我怎样才能知道他五月份请了多少假,六月请了多少天?

更新 我知道这一点,并进一步坚持

DateTime start = dateTimePicker1.Value.Date; 
DateTime end = dateTimePicker2.Value.Date; 
int a = int.Parse(Convert.ToInt32(end.Subtract(start).Days).ToString());

【问题讨论】:

标签: c# winforms


【解决方案1】:

在某个时间跨度中获取每月的天数。

   for (DateTime date = start; date < end; date = date.AddMonths(1))
   {
       DateTime this_date_start = new DateTime(date.Year, date.Month, 1);
       DateTime this_date_end = this_date_start.AddMonths(1).AddDays(-1);
       TimeSpan duration = this_date_end.Subtract(date);
       Console.WriteLine("duration " + date.Month + " = " + duration.Days  + "days");
   }

注意:这个循环是不完整的:那么你必须在循环之外再次执行此操作(这也将捕获任何短于一个月的跨度)

【讨论】:

  • 感谢大家的宝贵回答...再次感谢
【解决方案2】:

你可以试试这个代码,

最后你会得到一个Dictionary(表格形式),其中键是月份数,值是月份中的天数(在你的问题中,员工休假了多少天)

DateTime startDate = new DateTime(2018, 06, 25); //date time picker's date
DateTime endDate = new DateTime(2018, 07, 05); //date time picker's date
Dictionary<int, int> daysInMonth = new Dictionary<int, int>();

while(true)
{
    DateTime thisMonthEndDate = new DateTime(startDate.Year, startDate.Month, DateTime.DaysInMonth(startDate.Year, startDate.Month));
    if (thisMonthEndDate > endDate)
    {
        thisMonthEndDate = endDate;
        daysInMonth.Add(startDate.Month, (int)(thisMonthEndDate - startDate).TotalDays + 1);
        break;
    }

    daysInMonth.Add(startDate.Month, (int)(thisMonthEndDate - startDate).TotalDays + 1);
    startDate = thisMonthEndDate.AddDays(1);
}

输出打印将是

foreach(KeyValuePair<int, int> keyVal in daysInMonth)
{
    Console.WriteLine("For Month:" + keyVal.Key + " leave count:" + keyVal.Value);
}

【讨论】:

    【解决方案3】:

    LINQ 使其简单易读:

    var from = new DateTime(2018, 5, 28);
    var to = new DateTime(2018, 6, 4);
    
    var result = Enumerable.Range(0, int.MaxValue)
                           .Select(i => from.Date.AddDays(i))
                           .TakeWhile(date => date <= to.Date)
                           .GroupBy(date => date.Month)
                           .Select(range => (Month: range.Key, Days: range.Count()));
    
    foreach (var month in result)
    {
        Console.WriteLine($"Month: {month.Month}, Seek days: {month.Days}");
    }
    
    // result:
    // Month: 5, Seek days: 4
    // Month: 6, Seek days: 4
    

    如果您需要特定月份的搜索天数,请将其设为字典

    var seekDays = result.ToDictionary(month => month.Month, month => month.SeekDays);
    
    var seekDaysOfMay = seekDays.GetValueOrDefault(5, 0);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-22
      • 2013-05-31
      • 2010-11-07
      • 2013-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多