如何从日期范围获取日期时间列表?

时间:2011-07-31 16:06:42

标签: c# wpf

我有日期时间范围:

var _checkInYear = (from d in db.bookings select d.checkinyear).ToList();
var _checkInMonth = (from d in db.bookings select d.checkinmonth).ToList();
var _checkInDay = (from d in db.bookings select d.checkinday).ToList();

var _checkOutYear = (from d in db.bookings select d.checkoutyear).ToList();
var _checkOutMonth = (from d in db.bookings select d.checkoutmonth).ToList();
var _checkOutDay = (from d in db.bookings select d.checkoutday).ToList();

如何从此范围获取DateTime列表?例如,如果入住时间是20/08/2011并且退房时间为23/08/2011,则需要将日期时间列入此范围。

20/08 / 2011,21 / 08 / 2011,22 / 08 / 2011,23 / 08/2011。

5 个答案:

答案 0 :(得分:3)

DateTime checkIn = new DateTime(_checkInYear, _checkInMonth, _checkInDay);
DateTime checkOut = new DateTime(_checkOutYear, _checkOutMonth, _checkOutDay);

TimeSpan span = checkOut - checkIn;
List<DateTime> range = new List<DateTime>();
for(int day = 0; day <= span.Days; day++) 
{
    range.Add(checkIn.AddDays(day));
}

示例: http://www.ideone.com/BxmkF

答案 1 :(得分:2)

算法很简单,得到你的起点,递增直到你到达终点。

var startDate = new DateTime(checkInYear, checkInMonth, checkInDay);
var endDate = new DateTime(checkOutYear, checkOutMonth, checkOutDay);
var givenDate = startDate; 
var datesInRange = new List<DateTime>(); 

while (givenDate <= startDate)
{
    datesInRange.Add(givenDate);
    givenDate = givenDate.AddDays(1);
}

// work with / return datesInRange

答案 2 :(得分:1)

如果您可以办理入住和退房日期,那么您可以使用DateTime的扩展方法获取列表:

public static class ExtensionMethods
{
   static IEnumerable<DateTime> GetDateRange(this DateTime d, DateTime e)
   {
        var t=d;
        do
        {
            yield return t;
            t=t.AddDays(1);
        }while(t<e);
    }
}

然后像这样使用它:

var dateList = checkIn.GetDateRange(checkOutDate);

在Linqpad中测试过。

答案 3 :(得分:0)

鉴于您已经掌握了两个日期,最好的办法就是使用forwhile循环:

var dates = new List<DateTime>();
var curDate = booking.CheckinDate;
while (curDate <= booking.CheckoutDate)
{
    dates.Add(curDate);
    curDate = curDate.AddDays(1);
}

但是,我很欣赏这可能是一个用于问题目的的人为例子,但我担心你的示例代码不会做你想要的。如果是这种情况,请不要再费心阅读,我只想强调一下你可能会因此而变得更好:

var booking = (from b in data.Bookings
               where b.BookingId = bookingId
               select new BookingSearchResult // You have to create this class
                          {
                              CheckinDate = new DateTime(b.CheckinYear, b.CheckinMonth, b.CheckinDay),
                              CheckoutDate = new DateTime(b.CheckoutYear, b.CheckoutMonth, b.CheckoutDay)
                          }).SingleOrDefault();

答案 4 :(得分:0)

有点老问题,但我认为我们应该这样做:

DateTime checkIn = new DateTime(_checkInYear, _checkInMonth, _checkInDay);
DateTime checkOut = new DateTime(_checkOutYear, _checkOutMonth, _checkOutDay);
List<DateTime> allDates = new List<DateTime> ();

for (DateTime date = checkIn; date <= checkOut; date = date.AddDays(1))
    allDates.Add(date);
相关问题