Omesh
Omesh

Reputation: 55

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();

Upvotes: 2

Views: 18222

Answers (4)

suyash narhare
suyash narhare

Reputation: 11

try to calculate no of days between two dates

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

Upvotes: 1

Muhammad Mohsin Muneer
Muhammad Mohsin Muneer

Reputation: 433

 DateTime.Now.Subtract(startDate).Days.ToString();

Upvotes: 1

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;

Upvotes: 7

Joseph Rosson
Joseph Rosson

Reputation: 354

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.

Upvotes: 0

Related Questions