Resolved calculate days between two dates

rowlandsfc

Active member
Joined
Feb 3, 2019
Messages
43
Location
bridgend
Programming Experience
Beginner
as the title says imtryign to calculate the number of days between 2 dates, now this is where im at atm and this works ok so far, but this results with 365.75 but if i change the difference to int as i just want whole number i get a conversion error on span.totaldays

what ive got:
DateTime start = new DateTime(2020, 03, 13);
            DateTime end = DateTime.Now;

            TimeSpan span = end - start;

            double difference = span.TotalDays;
 
Last edited:
It's good that you marked your thread Resolved, so that everyone can see that you no longer need help. That said, it is considered good form to provide your solution, so that it might help others with the same issue that find this thread later.

There are actually two mistakes in your code. Addressing either would actually solve your problem but you ought to address both anyway.

Firstly, DateTime.Now will specifically give you the current date and time. If all you care about is the data then you should be using DateTime.Today instead, which gives you the current date with the time zeroed. The implementation of DateTime.Today returns the value of DateTime.Now.Date.

Secondly, the whole purpose the TimeSpan.TotalDays is to get the entire TimeSpan as a number of days. That has to include a fractional part, hence the type of the property is double. If you want just the whole days then you should be using the Days property instead, which is type int.
 
Note that, if you had to get the TotalDays value but needed a whole number then you could Math.Round or Math.Floor, depending on whether you wanted to round up and down or just down. You could also use Convert.ToInt32 to round the double and convert to an int in one go.
 
It's good that you marked your thread Resolved, so that everyone can see that you no longer need help. That said, it is considered good form to provide your solution, so that it might help others with the same issue that find this thread later.

There are actually two mistakes in your code. Addressing either would actually solve your problem but you ought to address both anyway.

Firstly, DateTime.Now will specifically give you the current date and time. If all you care about is the data then you should be using DateTime.Today instead, which gives you the current date with the time zeroed. The implementation of DateTime.Today returns the value of DateTime.Now.Date.

Secondly, the whole purpose the TimeSpan.TotalDays is to get the entire TimeSpan as a number of days. That has to include a fractional part, hence the type of the property is double. If you want just the whole days then you should be using the Days property instead, which is type int.
Ok awesome thanks for the notes, I'll make the changes later
 
Back
Top Bottom