根据总天数递增DateTime值

时间:2017-03-03 13:21:28

标签: c# sql-server date for-loop

当用户添加课程时,他们会选择课程的开始日期和结束日期。我已经能够计算结束日期和开始日期之间的值。我能够创建一个For循环,以便在类所在的每一天将一行插入到Class表中。 E.g 01/03/17 - 05/03/17运行5天,因此它在Class表中添加了5行。

目前,每行都会在开始日期为01/03/2017 00:00:00和结束日期05/03/2017 00:00:00添加。

对于每一行,我想将日期增加1,直到达到结束日期

例如:

01/03/2017 00:00:00  
02/03/2017 00:00:00   
03/03/2017 00:00:00   
04/03/2017 00:00:00   
05/03/2017 00:00:00

enter image description here

下面是我的For循环代码:

  public class UpdateTimetable
  {
    internal void insert_days(int moduledata, int? recurrencedata, DateTime startdatedata, DateTime enddatedata, int classtypedata, int roomcodedata, int starttimedata, int endtimedata, string totalday)
    {
        int tdays = Convert.ToInt16(totalday);
        for (int i = 1; i <= tdays; i++)
        {
            string connectionString = WebConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;

            SqlConnection myConnection = new SqlConnection(connectionString);

            myConnection.Open();

            string query = "INSERT INTO Class (ModuleId, ClassTypeId,  ClassScheduleStartTimeId, ClassScheduleEndTimeId, RoomCodeId, StartTime, EndTime, RecurrenceId) VALUES (@moduledata, @classtypedata, @starttimedata, @endtimedata, @roomcodedata, @startdatedata, @enddatedata,  @recurrencedata)";
            SqlCommand myCommand = new SqlCommand(query, myConnection);

            //myCommand.Parameters.AddWithValue("@daydata", DayId);
            myCommand.Parameters.AddWithValue("@moduledata", moduledata);
            myCommand.Parameters.AddWithValue("@classtypedata", classtypedata);
            myCommand.Parameters.AddWithValue("@startdatedata", startdatedata);
            myCommand.Parameters.AddWithValue("@enddatedata", enddatedata);
            myCommand.Parameters.AddWithValue("@roomcodedata", roomcodedata);
            myCommand.Parameters.AddWithValue("@starttimedata", starttimedata);
            myCommand.Parameters.AddWithValue("@endtimedata", endtimedata);
            myCommand.Parameters.AddWithValue("@recurrencedata", recurrencedata);

            myCommand.ExecuteReader();
            myConnection.Close();
        }
    }

}

这是我计算开始日期和结束日期之间总天数的代码。

            int moduledata = Convert.ToInt32(ddlModule.Text);
            DateTime startdatedata = Convert.ToDateTime(txtstartdate.Text);
            DateTime enddatedata = Convert.ToDateTime(txtenddate.Text);
            int classtypedata = Convert.ToInt32(ddlClassType.Text);
            int roomcodedata = Convert.ToInt32(ddlRoomCode.Text);
            int starttimedata = Convert.ToInt32(ddlStartClassTime.Text);
            int endtimedata = Convert.ToInt32(ddlEndClassTime.Text);

            startdatedata = DateTime.Parse(txtstartdate.Text).Date;
            enddatedata = DateTime.Parse(txtenddate.Text).Date;

            TimeSpan totaldays = enddatedata - startdatedata;

            // This is rounding the TimeSpan to the day value only
            string totalday = ((int)Math.Round(totaldays.TotalDays, MidpointRounding.AwayFromZero)).ToString();

enter image description here

public class UpdateTimetable
{
 internal void insert_days(int moduledata, int? recurrencedata, DateTime startdatedata, DateTime enddatedata, int classtypedata, int roomcodedata, int starttimedata, int endtimedata, string totalday)
    {
        int tdays = Convert.ToInt16(totalday);

        DateTime startDate = DateTime.Now.AddDays(tdays);
        DateTime endDate = enddatedata;

        List<string> Dates = new List<string>();

        for (int i = 1; i <= endDate.Subtract(startDate).Days; i++)
        {
            Dates.Add(startDate.AddDays(i).ToString());
            string connectionString = WebConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;

            SqlConnection myConnection = new SqlConnection(connectionString);

            myConnection.Open();

            string query = "INSERT INTO Class (ModuleId, ClassTypeId,  ClassScheduleStartTimeId, ClassScheduleEndTimeId, RoomCodeId, StartTime, EndTime, RecurrenceId) VALUES (@moduledata, @classtypedata, @starttimedata, @endtimedata, @roomcodedata, @startdatedata, @enddatedata,  @recurrencedata)";
            SqlCommand myCommand = new SqlCommand(query, myConnection);

            //myCommand.Parameters.AddWithValue("@daydata", DayId);
            myCommand.Parameters.AddWithValue("@moduledata", moduledata);
            myCommand.Parameters.AddWithValue("@classtypedata", classtypedata);
            myCommand.Parameters.AddWithValue("@startdatedata", startdatedata);
            myCommand.Parameters.AddWithValue("@enddatedata", enddatedata);
            myCommand.Parameters.AddWithValue("@roomcodedata", roomcodedata);
            myCommand.Parameters.AddWithValue("@starttimedata", starttimedata);
            myCommand.Parameters.AddWithValue("@endtimedata", endtimedata);
            myCommand.Parameters.AddWithValue("@recurrencedata", recurrencedata);

            myCommand.ExecuteReader();
            myConnection.Close();
        }
    }

}

enter image description here

3 个答案:

答案 0 :(得分:1)

如果您的问题是如何从给定的一天加上n天获得新的约会对象

DateTime dt = someOldDt.AddDays(n);

答案 1 :(得分:1)

不需要循环,您可以生成如下值:

rextester演示:http://rextester.com/QDQKX23942

declare @fromdate date = '20170301'
declare @thrudate date = '20170307'

;with n as (select n from (values(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) t(n))
, dates as (
  select top (datediff(day, @fromdate, @thrudate)+1) 
      [Date]=convert(datetime,dateadd(day, row_number() over (order by (select 1)) -1, @fromdate))
    from         n as deka
      cross join n as hecto      /* 100 days */
      cross join n as kilo     /* 2.73 years */
      --cross join n as [tenK]    /* 27.3 years */
   order by [Date]
)

select StartTime=dateadd(hour,9,d.date), EndTime=dateadd(hour,10,d.date)
from dates d

返回:

+---------------------+---------------------+
|      StartTime      |       EndTime       |
+---------------------+---------------------+
| 01.03.2017 09:00:00 | 01.03.2017 10:00:00 |
| 02.03.2017 09:00:00 | 02.03.2017 10:00:00 |
| 03.03.2017 09:00:00 | 03.03.2017 10:00:00 |
| 04.03.2017 09:00:00 | 04.03.2017 10:00:00 |
| 05.03.2017 09:00:00 | 05.03.2017 10:00:00 |
| 06.03.2017 09:00:00 | 06.03.2017 10:00:00 |
| 07.03.2017 09:00:00 | 07.03.2017 10:00:00 |
+---------------------+---------------------+

或者更好的是,使用日历表:

日历和数字表格引用:

要将它与现有的insert语句结合使用,可以使用类似的查询,不需要循环。

;with n as (select n from (values(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) t(n))
, dates as (
  select top (datediff(day, @startdatedata,@enddatedata)+1) 
      [Date]=convert(datetime,dateadd(day, row_number() over (order by (select 1)) -1, @startdatedata))
    from         n as deka
      cross join n as hecto 
      cross join n as kilo  
   order by [Date]
)

insert into Class (ModuleId , ClassTypeId , ClassScheduleStartTimeId 
  , ClassScheduleEndTimeId , RoomCodeId , StartTime , EndTime , RecurrenceId ) 
select 
   @moduledata
 , @classtypedata
 , @starttimedata
 , @endtimedata
 , @roomcodedata
 , StartTime= d.Date + s.StartTime
 , EndTime  = d.Date + e.EndTime
 , @recurrencedata
from dates d
  cross apply (
    select StartTime = convert(datetime,ClassTime)
    from ClassSchedule 
    where ClassScheduleId = @starttimedata
    ) as s
  cross apply (
    select EndTime = convert(datetime,ClassTime)
    from ClassSchedule 
    where ClassScheduleId = @endtimedata
    ) as e

在此示例中,@starttimedata@endtimedata将是表示小时的整数。如果您需要按分钟添加,可以切换到dateadd(minute...

还有其他方法可以为日期添加时间,但这取决于您的参数类型以及您要发送的值。

答案 2 :(得分:0)

最后我想我找到了你想要的东西。请看下面的代码:

        DateTime startDate = DateTime.Now.AddDays(-5); //5 days ago.
        DateTime endDate = DateTime.Now;

        List<string> Dates = new List<string>();

        for (int i = 0; i <= endDate.Subtract(startDate).Days; i++)
        {
            Dates.Add(startDate.AddDays(i).ToString()); //sample!
            //if enddatedata is the date that must icrease and startDate is the first Date:
            enddatedata = startDate.AddDays(i);

            // SQL insert HERE
        }

        //Dates:
        //2017-02-26 5:45:25 PM
        //2017-02-27 5:45:25 PM
        //2017-02-28 5:45:25 PM
        //2017-03-01 5:45:25 PM
        //2017-03-02 5:45:25 PM
        //2017-03-03 5:45:25 PM