Adding a TimeSpan to a given DateTime

后端 未结 8 969
生来不讨喜
生来不讨喜 2020-12-17 08:36

I just want to add 1 day to a DateTime. So I wrote:

 DateTime date = new DateTime(2010, 4, 29, 10, 25, 00);
 TimeSpan t = new TimeSpan(1, 0, 0,          


        
相关标签:
8条回答
  • 2020-12-17 08:52

    DateTime wont work if DateTime obj datatype is "DateTime?" which takes accepts null values, in such case DateTime? dt = DateTime.Now;

            DateTime dateObj = new DateTime();
    
            dateObj = Convert.ToDateTime(dt.ToString());
    
            var Month3 = dateObj.AddMonths(3);`
    
    0 讨论(0)
  • 2020-12-17 08:56

    You need to change a line:

    date = date.Add(t);
    
    0 讨论(0)
  • 2020-12-17 09:01

    A DateTime is immutable, but the Add and Subtract functions return new DateTimes for you to use.

    DateTime tomorrow = DateTime.Now.AddDays(1);
    
    0 讨论(0)
  • 2020-12-17 09:04

    DateTime values are immutable. The Add method returns a new DateTime value with the TimeSpan added.

    This works:

    Console.WriteLine("A day after the day: " + date.Add(t).ToString());
    
    0 讨论(0)
  • 2020-12-17 09:04
    date.Add(t);
    

    returns a modified DateTime and does not change the original instance on which you call the Add method on.

    0 讨论(0)
  • 2020-12-17 09:08

    What is wrong with just doing date = date.AddDays(1)?

    0 讨论(0)
提交回复
热议问题