Add () method does not add TimeSpan to DateTime

3

I created a DateTime with some values started in the constructor, but when I add a TimeSpan with some values, it does not add together with the date.

I'm using the DateTime method to add a TimeSpan, but it's not working because the time is set to zero, is there another way to do it? Or what am I doing wrong?

static void Main(string[] args)
{
    var timeSpan = new TimeSpan(5,5,0);

    var data = new DateTime(2017,8,5);

    data.Add(timeSpan);

    Console.WriteLine(data);
    Console.ReadKey();
}
    
asked by anonymous 05.07.2017 / 15:51

1 answer

8

DateTime is a structure ( struct ) which represents an instant in time.

The representation / value of a given moment in time does not change, it is that and not another. To ensure that this is true, struct DateTime is implemented in order to be immutable.

Thus, the method add () of DateTime does not change the object but rather returns a new DateTime with the value of TimeSpan added.

You should therefore use the method return.

You can save it to a variable and use it in WriteLine

var dateTimeWithTimeSpanAdded = d.Add(ts);
Console.WriteLine(dateTimeWithTimeSpanAdded);

or use return directly

Console.WriteLine(d.Add(ts));
    
05.07.2017 / 15:55