简体   繁体   中英

Calculating the Number of Days between two Dates and displaying it in a Label

Hi I'm trying to capture two dates selected by the user in a C# Calendar Control and I want the date range to be displayed in a label. I have worked out on the following code but it generates a Minus value ; not the actual date range.

DateTime from = CalFrom.SelectedDate;
DateTime to = CalTo.SelectedDate;
double days = (CalTo.SelectedDate - CalFrom.SelectedDate).TotalDays;
TimeSpan t = to - from;
double noOfDays = t.TotalDays;
TimeSpan ts = to - from;
double differnceindays = ts.TotalDays;
lblNoofDays.Text = differnceindays.ToString();

This code is working perfectly for me for calculating the number the days between two days.

DateTime d1 = DateTime.Now;
DateTime d2 = DateTime.Now.AddDays(10);
TimeSpan difference = d2 - d1;      
var days = difference.TotalDays;
 DateTime.Now.Subtract(startDate).Days.ToString();

try to calculate no of days between two dates

string days = (date2 - date1).Value.Days.ToString();

The only problem I see is that you assume the start and end dates will be correctly range checked, meaning start date is never greater than end date (which would produce negative values for total days). If you want to correct for the fact that start date may be after end date, then this should work.

DateTime startDate = DateTime.Now.AddDays(-94); // Example random 94 day span..
DateTime endDate = DateTime.Now;
TimeSpan duration = endDate > startDate ? endDate - startDate : startDate - endDate;
double daysBetweenDates = duration.TotalDays;

Note: "daysBetweenDates" will include fractional days (thus the double type). Also, the code above assumes local time. If you want UTC you will need to account for that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM