繁体   English   中英

检查日期列表中是否存在日期

[英]Check if date exist in list of dates

如何从日期列表中仅比较 mounth 和 day(而不是年份)?

 DateTime[] dates= new DateTime[]
                {
                    new DateTime(DateTime.Now.Year, 1, 1), 
                    new DateTime(DateTime.Now.Year, 5, 1), 
                    new DateTime(DateTime.Now.Year, 5, 8)
                };
// Result
DateTime date_1 = new DateTime(2016, 1, 1); // OK
DateTime date_2 = new DateTime(2022, 1, 1); // OK
DateTime date_3 = new DateTime(2016, 1, 2); // KO
DateTime date_4 = new DateTime(2016, 1, 3); // KO

您可以使用IEnumerable 扩展 Any来检查您的数组是否包含具有所需月份和日期的日期

DateTime date_1 = new DateTime(2016, 1, 1); 
bool exist = dates.Any (d => d.Month == date_1.Month && d.Day == date_1.Day);
Console.WriteLine(exist);

DateTime date_3 = new DateTime(2016, 1, 2); 
exist = dates.Any (d => d.Month == date_3.Month && d.Day == date_3.Day);
Console.WriteLine(exist);

当然这需要使用 System.Linq

只需比较日期的月份和日期部分:

DateTime date = new DateTime(2016, 1, 1);
DateTime date2 = new DateTime(2017, 1, 1);
if (date.Day == date2.Day && date.Month == date2.Month) 
{
    // Same
}

下面的代码是计算不包括假期的工作时间,你可能会发现它很方便

 void CalculateHourse()
    {
        try
        {
            DateTime start = DateTime.ParseExact("04/02/2020 16:00","dd/MM/yyyy HH:mm",null,System.Globalization.DateTimeStyles.None);
            DateTime end = DateTime.ParseExact("09/02/2020 10:00", "dd/MM/yyyy HH:mm", null, System.Globalization.DateTimeStyles.None);

            List<DateTime> holidays = new List<DateTime>();

            holidays.Add(new DateTime(2020, 02, 05));
            holidays.Add(new DateTime(2020, 02, 06));
            holidays.Add(new DateTime(2020, 02, 07));
            holidays.Add(new DateTime(2020, 02, 08));


            int count = 0;

            for (var i = start; i < end; i = i.AddHours(1))
            {
                if (i.DayOfWeek != DayOfWeek.Friday && i.DayOfWeek != DayOfWeek.Saturday)
                {
                    //if (holidays.Any(x=>x.Date.ToString("d") == i.Date.ToString("d")))
                    if(!holidays.Any(x=>x.Day == i.Day && x.Month == i.Month && x.Year == i.Year))
                    {
                        if (i.TimeOfDay.Hours >= 9 && i.TimeOfDay.Hours <= 17)
                        {
                            count++;
                        }
                    }
                }
            }

            Console.WriteLine(count);
            Console.Read();
        }
        catch (Exception ex)
        {
            Logger.Error(ex);
        }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM