'RemainingDays not returning correct count [duplicate]

In this sample I am trying to get the RemainingDays from two dates. One of the day is the next day and the other is two days from now. I am using dateTime.now and getting

Code

   int? RemainingDays = null;
   DateTime? EndDateTest1 = new DateTime(2022, 5, 11);
   RemainingDays = ( EndDateTest1.Value - DateTime.Now ).Days;

Current Output

0
1

Thinking it should be

1
2

Working sample

https://dotnetfiddle.net/bYcLeZ



Solution 1:[1]

You should be able to resolve by only getting date portion via

 RemainingDays = ( EndDateTest1.Value - DateTime.Now.Date ).Days;

The .Date ending of a date/time field will truncate any time portion for you.

Solution 2:[2]

A DateTime is not a date, but, as the name implies, a date and a time.

If you initialize a DateTime with only a date, the time will be 00:00:00.

The time of DateTime.Now() will actually have a value, so when you subtract that from your EndDateTest1, the result will actually be less than the full number of days you expect. If you run this around 8 P.M., the result of the subtraction is 4 hours, which is, indeed, 0 days.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 DRapp
Solution 2 oerkelens