Calculation of days comes negative. Why?

Asked

Viewed 59 times

-2

I did that:

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

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

-25

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

  • 7

    How much is 1 - 26?

  • Yes, I thought he’d take the current date and subtract it from day 1. But it’s the other way around.

  • int dias = (int)DateTime.Today.Subtract(dt).TotalDays; that would be the bill

1 answer

3

Why are you 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’re doing is returning the difference in days from the date assigned to the variable dt and as in his statement of int dias you use the base date by replacing the current date you are getting the negative value by "leftover" days.

Ex:

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

Browser other questions tagged

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