Calculation of days comes negative. Because?

-2

I did this:

DateTime dt = new DateTime(DateTime.Today.Year, DateTime.Today.Month, 1);
int dias = (int)dt.Subtract(DateTime.Today).TotalDays;

If you do for today (01/26/2018) the result in var dias is:

-25

I just wanted to know why it came negative, just to understand.

    
asked by anonymous 26.01.2018 / 20:52

1 answer

3

Because you are reversing the order of your comparison (to get the result you expect):

DateTime dt = new DateTime(DateTime.Today.Year, DateTime.Today.Month, 1);
int dias = DateTime.Today.Subtract(dt).TotalDays;

Explaining:

What you are doing is returning the difference in days from the date assigned to the dt variable and as in your int dias statement you use the base date by subtracting the current date you are getting the negative value for " "days.

Ex:

  

01/01/2018 - 26/01/2018 [in days] = -25 days (because it is a future date)

    
26.01.2018 / 20:58