ASP.. NET c#日期比较
本文关键字:比较 日期 NET ASP | 更新日期: 2023-09-27 18:10:51
我已经阅读了论坛上的一些建议,这是我能联系到的最接近的事情,但还没有完全在那里比较旅行日期和返回日期在asp.net c#
无论如何,问题是我正在尝试预订一个房间,从日期x到日期y。此时不应该发生其他预订,即系统发出消息说它无法完成覆盖预订。你能给我介绍一下教程吗?或者甚至是用来构建的示例代码?
谢谢,
当您要创建一个新的预订时,请对照现有的预订进行检查。
如果在现有预订之前结束或之后开始预订,则预订不会重叠,因此只需遍历现有预订并检查:
if (!(newBooking.EndDate < existingBooking.StartDate || newBooking.StartDate > existingBooking.EndDate)) {
// there is a conflicting booking
}
假设一个Booking类具有RoomNumber, StartDate和EndDate属性。
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;
}
}
如何:
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
如果是我,我会在数据库中有一个RoomBooking事务表(至少包含一个RoomId列加上RoomTypeId,BookingStartDate和BookingEndDate)。然后编写一个存储过程,查询数据库以完成用例"在特定日期范围内是否有合适房间类型的可用房间"—签名如下:
GetAvailableRoomsForTypeAndDates(RoomTypeId, BookingStartDate, BookingEndDate)
返回值然后在代码中或通过ORM工具处理。