Add() method does not add Timespan to Datetime

Asked

Viewed 149 times

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 am using the Datetime method to add a Timespan, but it is not working because the time is reset, there is another way to do beyond this ? Or what I’m 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();
}
  • 1

    It worked here: https://dotnetfiddle.net/2R6rvB

1 answer

8


Datetime is a structure(struct) that represents an instant in time.

The representation/value of a given instant in time does not change, it is that and not another. To ensure that this is so the struct DateTime is implemented in a way that is immutable.

Thus, the method add() de Datetime does not change the object but returns a new Datetime with the value of Timespan added.

You should therefore use the return method.

You can store it in a variable and use it in Writeline

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

or use the return directly

Console.WriteLine(d.Add(ts));
  • Just put it back.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.