C#月和日在日期之间发生

时间:2012-11-07 06:05:55

标签: c# datetime

我有一个月份和日期列表,我需要在给定日期之间搜索此列表中的每个月和每天。任何人都可以建议我做最好的方法来获得理想的输出。

例如:

  

月日列表 - > 01 / 11,03 / 15,05 / 25,09 / 01

     

日期之间 - > 01/01/2012至07/01/13

预期结果:

  

01/11/2012,01/11/2013

     

03/15 / 2012,03 / 15/2013

     

05/25 / 2012,05 / 25/2013

     

09/01/2012

我试过这样但是它给了内存异常,如果从日期到日期有多少年差距,时间和内存复杂性会增加,是否有任何快速解决方案可以获得它?

DateTime[] dateDates = new DateTime[dateTypeList.Rows.Count];
//convert strings to datetimes:
for (int i = 0; i < dateTypeList.Rows.Count; i++)
{
    dateDates[i] = Convert.ToDateTime(Convert.ToDateTime(string.Format("{0}/{1}", Convert.ToInt32(dateTypeList.Rows[i]["Month"]), Convert.ToInt32(dateTypeList.Rows[i]["Day"]))));
}

//define start and end time:
DateTime dateStart = new DateTime(2012, 1, 1);
DateTime dateEnd = new DateTime(2013, 7, 1);

List<DateTime> results = new List<DateTime>();
//loop days between start and end time:
for (DateTime a = dateStart; a <= dateEnd; a.AddDays(1))
{
    for (int i = 0; i < dateDates.Length; i++)
    {
        if (dateDates[i] == a)
        {
            results.Add(a);
        }
    }
}

4 个答案:

答案 0 :(得分:3)

编辑:好的,现在我看到了更多关于你想要实现的目标。

所以你输入了:

  • 开始日期和结束日期
  • 月/日对的列表。目前你实际没有这个,但这就是你在逻辑上得到的。

您当前的代码没有考虑到可能存在多年的事实。

首先,让我们适当地转换您的数据表:

var monthDays = dateTypeList.Rows.AsEnumerable()
                            .Select(row => new { Month = row.Field<int>("Month")
                                                 Day = row.Field<int>("Day") })
                            .ToList();

现在你可以使用:

for (int year = startDate.Year; year <= endDate.Year; year++)
{
    foreach (var pair in monthDays)
    {
        // Avoid creating a date which doesn't exist...
        if (!DateTime.IsLeapYear(year) && pair.Month == 2 && pair.Day == 29)
        {
            continue;
        }
        DateTime date = new DateTime(year, pair.Month, pair.Day);
        if (date <= startDate && date <= endDate)
        {
            results.Add(date);
        }
    }
}

这是当前的问题:

for (DateTime a = dateStart; a <= dateEnd; a.AddDays(1))

DateTime是不可变的,因此如果不使用返回值,则AddDays无效。你想要:

for (DateTime a = dateStart; a <= dateEnd; a = a.AddDays(1))

我也会更改此代码:

dateDates[i] = Convert.ToDateTime(
  Convert.ToDateTime(string.Format("{0}/{1}", 
      Convert.ToInt32(dateTypeList.Rows[i]["Month"]), 
      Convert.ToInt32(dateTypeList.Rows[i]["Day"]))));
  • 无缘无故地通过字符串表示
  • 无缘无故地召唤Convert.ToDateTime两次
  • 假设系统日期格式为月/日,这是特定于文化的

答案 1 :(得分:2)

public class Class1
{
    public static void Main()
    {
        var dayList = new List<customMonthDay>{
            new customMonthDay{ Day = 11, Month = 1 },
            new customMonthDay{ Day = 15, Month = 3 },
            new customMonthDay{ Day = 25, Month = 5 },
            new customMonthDay{ Day = 1, Month = 9 }
        };

        var startDate = new DateTime( 2012, 1, 1 );
        var endDate = new DateTime( 2013, 7, 1 );

        var listYears = getYears(startDate, endDate);

        var includedDays = new List<customMonthDayYear>();

        foreach (var year in listYears)
        {
            foreach (var day in dayList)
            {
                var candidateday = new customMonthDayYear { Year = year, Month = day.Month, Day = day.Day };
                if (candidateday.ToDateTime() > startDate && candidateday.ToDateTime() < endDate)
                    includedDays.Add(candidateday);
            }
        }

        includedDays.ForEach(x => Console.WriteLine(x.ToDateTime().ToString()));
    }

    protected static List<int> getYears(DateTime start, DateTime end)
    {
        var years = new List<int>();
        int diff = end.Year - start.Year;
        for ( int i = 0; i <= diff; i++ )
        {
            years.Add( start.Year + i );
        }
        return years;
    }

    public class customMonthDay
    {
        public int Day { get; set; }
        public int Month { get; set; }
    }

    public class customMonthDayYear : customMonthDay
    {
        public int Year { get; set; }

        public DateTime ToDateTime()
        {
            return new DateTime(Year, Month, Day);
        }
    }
}

答案 2 :(得分:0)

使用以下内容:

for each date in list

 a.Equals(date) or a.CompareTo(date)

答案 3 :(得分:0)

这对我有用,但是我们还有什么方法可以通过使用linq或其他东西减少这个?

private List<DateTime> GetDates(DataTable dateTypeList, DateTime fromDate, DateTime toDate)
        {
            List<DateTime> results = new List<DateTime>();
            fromDate = Convert.ToDateTime(fromDate.ToShortDateString());
            toDate=Convert.ToDateTime(toDate.ToShortDateString());

            int minDay = fromDate.Day;
            int minMonth = fromDate.Month;
            int minYear = fromDate.Year;
            int maxDay = toDate.Day;
            int maxMonth = toDate.Month;
            int maxYear = toDate.Year;
            for (int j = minYear; j <= maxYear; j++)
            {
                for (int i = 0; i < dateTypeList.Rows.Count; i++)
                {

                    int _day = Convert.ToInt32(dateTypeList.Rows[i]["Day"]);
                    int _month = Convert.ToInt32(dateTypeList.Rows[i]["Month"]);
                    DateTime tempDate = new DateTime(j, _month, _day);
                    if ((tempDate >= fromDate) && (tempDate <= toDate))
                    {
                        results.Add(tempDate);
                    }

                }
            }

            return dateTypeList;
            throw new NotImplementedException();
        }