如何从日期列表中仅比较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
答案 0 :(得分:4)
您可以使用IEnumerable extension 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
答案 1 :(得分:3)
只需比较日期的月份和日期部分:
DateTime date = new DateTime(2016, 1, 1);
DateTime date2 = new DateTime(2017, 1, 1);
if (date.Day == date2.Day && date.Month == date2.Month)
{
// Same
}
答案 2 :(得分:0)
下面的代码用于计算工作时间(节假日除外),您可能会发现它很方便
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);
}
}