Here\'s my code:
DateTime date1 = new DateTime(byear, bmonth, bday, 0, 0, 0);
DateTime datenow = DateTime.Now;
DateTime date2 = datenow - date1
.Subtract has two overloads. One accepts a DateTime and returns a TimeSpan, the other accepts a TimeSpan and returns a DateTime.
In other words, if you subtract a date from a date, you get the timespan difference. Otherwise, if you subtract a timespan from a date, you get a new date.
Use this code:
DateTime? Startdate = cStartDate.GetValue<DateTime>().Date;
DateTime? Enddate = cEndDate.GetValue<DateTime>().Date;
TimeSpan diff = Enddate.GetValue<DateTime>()- Startdate.GetValue<DateTime>() ;
txtDayNo.Text = diff.Days.GetValue<string>();
Well the point is that if you think of it, subtracting a date to another should not yield a date, it should yield a time span. And that is what happens when you use DateTime.Subtract().
TimeSpan timeSpan = datenow - date1; //timespan between `datenow` and `date1`
This will make your current code work.
If on the other hand you want to subtract, let's say, one year from your date, you can use:
DateTime oneYearBefore = DateTime.Now.AddYears(-1); //that is, subtracts one year
TimeSpan Example:
private void Form1_Load(object sender, EventArgs e)
{
DateTime startdatetime = new DateTime(2001, 1, 2, 14, 30, 0);
DateTime enddatetime = DateTime.Now;
TimeSpan difference = enddatetime.Subtract(startdatetime);
string sdifference = "TotalDays:" + difference.TotalDays + Environment.NewLine;
sdifference += "TotalHours:" + difference.TotalHours + Environment.NewLine;
sdifference += "TotalMilliseconds:" + difference.TotalMilliseconds + Environment.NewLine;
sdifference += "TotalMinutes:" + difference.TotalMinutes + Environment.NewLine;
sdifference += "TotalSeconds:" + difference.TotalSeconds + Environment.NewLine;
sdifference += "Ticks:" + difference.Ticks + Environment.NewLine;
sdifference += "Total:" + difference.Days + " days, " + difference.Hours + " hours, " + difference.Minutes + " minutes, " + difference.Seconds + " seconds and " + difference.Milliseconds + " milliseconds.";
TextBox TextBox1 = new TextBox();
TextBox1.Multiline = true;
TextBox1.Dock = DockStyle.Fill;
TextBox1.Text = sdifference;
this.Controls.Add(TextBox1);
}
You are expecting the difference of two dates to be a date which is not. That being said, if you need to subtract a certain number of days or months, it can easily be done using the built in methods of the DateTime object such as .AddDays(-1), note that I used a negative number to substract, you can apply the opposite. Here is a quick example.
DateTime now = DateTime.Now;
// Get the date 7 days ago
DateTime sevenDaysAgo = now.AddDays(-7);
// Bulk: Get the date 7 days and two hours ago
DateTime sevenDaysAndtwoHoursAgo = now.Add(-(new TimeSpan(7, 2, 0, 0)));
As already mentioned, date - date gives you a TimeSpan, not a DateTime. If you want a DateTime, use AddDays(-1)
as in:
DateTime subtractedDate = date1.AddDays(-1);