我试图获取开始日期和结束日期,并在数据库中为从开始日期到结束日期的每一天创建一行。 rf_date列应该将循环中的日期写入db。我的问题是写入数据库的日期是今天的日期。
if (booking.arrival_date != null && booking.departure_date != null)
{
DateTime startDate;
DateTime.TryParse(booking.arrival_date.ToString(), out startDate);
DateTime endDate;
DateTime.TryParse(booking.departure_date.ToString(), out endDate);
for (DateTime date = startDate; date <= endDate; date = date.AddDays(1))
{
bookingRoomFlow newroomflow = new bookingRoomFlow();
newroomflow.bookingid = bookingid;
newroomflow.rf_date = date;
roomflows.Add(newroomflow);
if (ModelState.IsValid)
{
db.bookingroomflows.Add(newroomflow);
db.SaveChanges();
}
}
}
我的代码有任何明显的问题吗?
答案 0 :(得分:1)
我认为这是另一回事,因为你的循环代码看起来很正确。我测试了样品开始,结束日期如下。
namespace DateIncrementTest
{
using System;
class Program
{
static void Main(string[] args)
{
ProcessDates();
Console.WriteLine("Press a key to Exit...");
Console.ReadKey();
}
private static void ProcessDates()
{
DateTime startDate;
DateTime.TryParse("1/1/2013", out startDate);
DateTime endDate;
DateTime.TryParse("1/7/2013", out endDate);
for (DateTime date = startDate; date <= endDate; date = date.AddDays(1))
{
Console.WriteLine("Current Value for Date = {0}", date.ToShortDateString());
}
}
}
}
控制台输出如下。
Current Value for Date = 1/1/2013
Current Value for Date = 1/2/2013
Current Value for Date = 1/3/2013
Current Value for Date = 1/4/2013
Current Value for Date = 1/5/2013
Current Value for Date = 1/6/2013
Current Value for Date = 1/7/2013
Press a key to Exit...
你有没看过