Reputation: 786
I need to calculate the number of days between 2 dates as an integer value and so far I have tried the following:
int Days = Convert.ToInt32(CurrentDate.Subtract(DateTime.Now));
int Days = Convert.ToInt32((CurrentDate - DateTime.Now).Days);
However, neither statement is giving me the correct output. The first one is giving me the error Unable to cast object of type 'System.TimeSpan' to type 'System.IConvertible'. The second one is giving Days
as 0.
Upvotes: 1
Views: 10060
Reputation: 5802
Just try with this.
DateTime dt1 = DateTime.Now;
DateTime dt2 = CurrentDtae;
int result = (int)((dt2 - dt1).TotalDays);
Upvotes: 1
Reputation: 460138
TimeSpan.Days
is already an int
value so you don't need to cast it:
int Days = (CurrentDate - DateTime.Now).Days;
So i assume that 0 days is correct. What is CurrentDate
?
If you want to round the TimeSpan
according to the hour part you could use this method:
public static int DaysRounded(TimeSpan input, MidpointRounding rounding = MidpointRounding.AwayFromZero)
{
int roundupHour = rounding == MidpointRounding.AwayFromZero ? 12 : 13;
if (input.Hours >= roundupHour)
return input.Days + 1;
else
return input.Days;
}
int days = DaysRounded(TimeSpan.FromHours(12)); // 1
Upvotes: 3