locked
Add Month to Date RRS feed

  • Question

  • User-1499457942 posted

    Hi

      I have Date field in Data Table row . I want to add 1 month  to that Date field & insert record using c#

    Thanks

    Sunday, November 18, 2018 2:39 PM

All replies

  • User-893317190 posted

    Hi JagjitSingh,

    You could use  datetime.AddMonths method.

    Below is my code.For example, your time is today.

      using (SqlConnection con = new SqlConnection(constr))
                {
                    DateTime time = DateTime.Now;
                 time=   time.AddMonths(1);
                 
                    using (SqlCommand com = new SqlCommand("INSERT INTO [Period] (Date1, Date2) VALUES(@Date11, @Date12)", con))
                    {
                        com.Parameters.AddWithValue("Date11",time);
                        com.Parameters.AddWithValue("Date12",time);
                        con.Open();
                        com.ExecuteNonQuery();
                    }
                }

    The result.

    date1	                 date2
    2018-12-19 12:17:31.680	2018-12-19 12:17:31.680

    Best regards,

    Ackerly Xu

    Monday, November 19, 2018 4:20 AM
  • User-1499457942 posted

    Hi Ackerly

       I want to add 1 month to date . Suppose values in Database field is 2018/10/25. 1 month should be added to it it should give 2018/11/25 and Save it in Database.

    Field DataType is Date in Sql Server . I am using 2008.

    Thanks

      

    Monday, November 19, 2018 5:48 AM
  • User-893317190 posted

    Hi JagjitSingh,

    It could also apply to date.

    I have made a test.It's my original table.

    tDate	     tDateTime
    2018-10-25	NULL

    And my code.

    using (SqlConnection con = new SqlConnection(constr))
                {
                    DateTime time ;
    
    
                        using (SqlCommand com = new SqlCommand("select tDate from myTime", con))
                        {
                          
                            con.Open();
                       time=(DateTime)  com.ExecuteScalar();
                       time=  time.AddMonths(1);
                     
                    }
                    using (SqlCommand comInsert = new SqlCommand("insert into myTime (tDate) values(@tDate)", con))
                    {
                        comInsert.Parameters.AddWithValue("tDate", time);
                     
                        comInsert.ExecuteNonQuery();
                    }
    
                }

    The result.

    tDate	      tDateTime
    2018-10-25	NULL
    2018-11-25	NULL

    Best regards,

    Ackerly Xu

    Monday, November 19, 2018 6:20 AM