ASP.NET C#日期比较
我已经通过在论坛上提出了一些建议阅读,这是我可能涉及到最近的事情,但还没有应用Compare journey date with return date in asp.net c#ASP.NET C#日期比较
无论如何,问题是,我想预订房间,从x日期到y日期。目前还没有其他预订应该发生,即系统发送消息说它不能完成覆盖预订。你可以指导我的任何教程?或者甚至是代码示例以构建?
谢谢,
当您即将创建新预订时,请检查现有预订。
甲预订不如果两端的现有预订之前或之后重叠它启动,所以只是环throught现有预订,并检查:
if (!(newBooking.EndDate < existingBooking.StartDate || newBooking.StartDate > existingBooking.EndDate)) {
// there is a conflicting booking
}
假设与属性RoomNumber,起始日期和结束日期一个预定类。
class Booking
{
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public int RoomNumber { get; set; }
}
bool IsRoomAvailableOnDate(int roomNumber, DateTime date)
{
//change this to match your data source
List<Booking> bookings = Booking.GetBookings();
// get all bookings that have a start date and end date within your timeframe
var bookingsWithinDate = from booking in bookings
where booking.RoomNumber == roomNumber
&& booking.StartDate <= date
&& booking.EndDate >= date
select booking;
if (bookingsWithinDate.Any())
{
//bookings found that match date and room number
return false;
}
else
{
//no bookings
return true;
}
}
如果是我的话我会在数据库中(至少含有RoomId列加RoomTypeId,BookingStartDate和BookingEndDate)一RoomBooking事务表。然后编写查询的数据库,以满足使用情况的存储过程“是否有一个特定的日期范围内提供适当的房间类型的房间” - 与像签名:
GetAvailableRoomsForTypeAndDates(RoomTypeId,BookingStartDate,BookingEndDate)
然后在您的代码或通过ORM工具处理返回。
上面的大多数评论显示了我已经知道:(我需要弄清楚如何计算范围,并阻止它在日期x和日期y之间选择 –
如何:
private bool ConflictsWithExisting(Booking booking)
{
return existingBookings.Any(b => b.ConflictsWith(booking));
}
与订房以下方法:
public bool ConflictsWith(Booking booking)
{
// You may want to check they are for the same room here.
return !(booking.EndDate <= this.StartDate || booking.StartDate >= this.EndDate);
}
我碰到一些有助于来到自己,这是是 MSDN: DateTime Subtract
和代码如下所示:
System.DateTime date1 = new System.DateTime(1996, 6, 3, 22, 15, 0);
System.DateTime date2 = new System.DateTime(1996, 12, 6, 13, 2, 0);
System.DateTime date3 = new System.DateTime(1996, 10, 12, 8, 42, 0);
// diff1 gets 185 days, 14 hours, and 47 minutes.
System.TimeSpan diff1 = date2.Subtract(date1);
// date4 gets 4/9/1996 5:55:00 PM.
System.DateTime date4 = date3.Subtract(diff1);
// diff2 gets 55 days 4 hours and 20 minutes.
System.TimeSpan diff2 = date2 - date3;
// date5 gets 4/9/1996 5:55:00 PM.
System.DateTime date5 = date1 - diff2;
不过,我会尝试这一点,但再次感谢您的帮助
编辑:
我也碰到过这样的代码在网站http://www.dotnetspider.com/forum/84579-How-To-Check-Date-Date-Range.aspx
DateTime sd=Convert.ToDateTime("2/2/2007");
DateTime ed =Convert.ToDateTime("2/2/2009");
if ((sd<=Convert.ToDateTime(nTextBox1.Text)) && (Convert.ToDateTime(nTextBox1.Text<=ed))
{
MessageBox.Show("In Range");
}
else
{
MessageBox.Show("Not In Range");
}
适合范围检查: D
不能真的看到问题.. 我想你有一个预订列表,其中有一个DateTime开始和一个DateTime结束.. 使用foreach通过你的列表,并检查是否新的日期时间是有效的为您的条件.. – Rob