1

i want to set the date to 1st of Jan 16 years ago from today's date. I used the code

DateTime dtm = new DateTime(DateTime.Today.Year, 1, 1);
dtm.AddYears(-16);
dtpDOB.Value = dtm;// assign value to date time picker

but it shows the date value as 1/1/2014, why this does not set the year part back in 16 years?

thanks

Phill Greggan
  • 2,234
  • 3
  • 20
  • 33

3 Answers3

5
dtm = dtm.AddYears(-16);

Just assign the value

AD.Net
  • 13,352
  • 2
  • 28
  • 47
3

According to the MSDN documentation, .AddYears will return a new DateTime object rather than modifying the existing instance. So change your line to

dtm = dtm.AddYears(-16);
Reticulated Spline
  • 1,892
  • 1
  • 18
  • 20
2

The DateTime type is a struct. Because of that, its properties are immutable (they can't be changed post-constructor). structs are passed by value in C#.

Because of that, as a few other people have said, you need to reassign the value.

dtm = dtm.AddYears(-16);

It's just like a typical string operation in C#. When you call string.Replace(string, string), you need to capture the return value of the operation. The same is true for LINQ-y IEnumerable<T> operations.

Although that said, it seems like you'd be better off to just call the constructor appropriately.

dtpDOB.Value = new DateTime(DateTime.Today.Year - 16, 1, 1);
Community
  • 1
  • 1
Matthew Haugen
  • 12,916
  • 5
  • 38
  • 54