Adding a TimeSpan to a given DateTime

后端 未结 8 970
生来不讨喜
生来不讨喜 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 09:09

    The result of date.Add(t) is what you're after:

     DateTime date = new DateTime(2010, 4, 29, 10, 25, 00);
     TimeSpan t = new TimeSpan(1, 0, 0, 0);
    
     // The change is here, setting date to be the *new* date produced by calling Add
     date = date.Add(t);
    
     Console.WriteLine("A day after the day: " + date.ToString());
    
    0 讨论(0)
  • 2020-12-17 09:16

    dtb is right about DateTime being immutable. Think of it this way: a DateTime is a value type, which puts it in the same category as int or double. Instances of these structures cannot be modified; they can only be evaluated and copied.

    Consider this code:

    int i = 4;
    
    i + 2;     // does not compile, but what if it did?
               // would i become 6? clearly not --
               // i + 2 expresses a NEW value, which can
               // be copied somewhere
    
    i = i + 2; // there we go -- that's better
    

    This is analogous to:

    DateTime d = DateTime.Now;
    TimeSpan t = TimeSpan.FromDays(1.0);
    
    d.Add(t);     // compiles (because AddDays is a function),
                  // but is really the same as i + 2 above
    
    d = d.Add(t); // that's better
    

    By the way, one thing that might help make this clearer is realizing that the above line, d = d.Add(t), is the same as d = d + t. And you wouldn't write d + t on its own line, just like you wouldn't write i + 2 on its own line.

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