C #: how to subtract two dates?

Here is my code:

DateTime date1 = new DateTime(byear, bmonth, bday, 0, 0, 0); DateTime datenow = DateTime.Now; DateTime date2 = datenow - date1 

In the last line, I get this error:

Error 1: Cannot implicitly convert the type "System.TimeSpan" to "System.DateTime"

How to subtract two dates?

+7
c # winforms
source share
11 answers

Well, the fact is that if you think about it, subtracting a date from another should not give a date, it should give a time interval. And this is exactly 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, say, one year from your date, you can use:

 DateTime oneYearBefore = DateTime.Now.AddYears(-1); //that is, subtracts one year 
+19
source share

As already mentioned, date-to-date gives you a TimeSpan, not a DateTime. If you want to use DateTime, use AddDays(-1) , as in:

 DateTime subtractedDate = date1.AddDays(-1); 
+3
source share

The result of the date comparison is TimeSpan, not the DateTime value.

You want to do this:

 TimeSpan result = datenow - date1; 
+1
source share

.Subtract has two overloads. One takes a DateTime and returns a TimeSpan, the other takes a TimeSpan and returns a DateTime.

In other words, if you subtract the date from the date, you will get the difference in time intervals. Otherwise, if you subtract the time interval from the date, you will get a new date.

+1
source share

Can you clarify what you are trying to calculate? The difference between any two dates in C # or real life is the time interval. If you are trying to calculate age, then what you want is the period of time from the moment they were born. Change Date2 to

 Timespan age = datenow - date1; 
+1
source share

You correctly subtract two dates in your code. What happens is that you expect the difference between the two dates to be a different date, and that is not the case.

As other posters noted, you get a TimeSpan . From your variable names, I get the meaning that you are trying to figure out someone's age.

Age is not a date, it is a duration. Read the TimeSpan object and you will find that it correctly expresses the idea you are looking for.

I am not 0029-01-01 years old, I am 29 years old. (Today is not my birthday, but suppose it's for easy math.)

If you are trying to show someone the age in the control, and that control wants a DateTime , you are probably using the wrong control for this.

+1
source share

Try using tics ...?

 DateTime date1 = new DateTime(1986, 3, 16, 0, 0, 0); DateTime datenow = DateTime.Now; DateTime date2 = new DateTime(datenow.Subtract(date1).Ticks); 
+1
source share

You expect the difference between the two dates to be a date that is not. At the same time, if you need to subtract a certain number of days or months, this can be easily done using the built-in methods of the DateTime object, such as .AddDays (-1) , note that I used a negative number to subtract, you can apply the opposite. Here is a brief 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))); 
0
source share

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>(); 
0
source share

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); } 
0
source share

Not quite the answer to your question, but I prefer to use var instead of annotating variables with types. var IMO makes the code much cleaner than otherwise.

Here is your code snippet with var s:

 var date1 = new DateTime(byear, bmonth, bday, 0, 0, 0); var datenow = DateTime.Now; var date2 = datenow - date1; 

EDIT

For C # developers with var-is-bad setting:

[Original post here ]

I use var widely. There has been criticism that this reduces the readability of the code, but there is no argument to support this claim.

Admittedly, this may mean that it is not clear what type we are dealing with. So what? This is actually the point of unleashed design. When working with interfaces, you are definitely not interested in the type of variable. var accepts this a lot more, true, but I believe that the argument remains in terms of readability: The programmer should not really be interested in the type of the variable, but rather in what the variable does. This is why Microsoft also calls duck print output type.

So what does a variable do when I declare it using var? Easy, he told me what IntelliSense does. Any reasoning about C # that the IDE ignores is lacking in reality. In practice, each C # code is programmed in an IDE that supports IntelliSense.

If I use the declared var variable and get confused that the variable is there, there is something fundamentally wrong with my code. Var is not the cause; it only makes the symptoms visible. Do not blame the messenger.

Now the C # team has issued an encoding guide that states that var should be used to capture the result of the LINQ statement, which creates an anonymous type (because here we have no real alternative to var). Well, let it go. As long as the C # team does not give me a sound argument for this guide, I am going to ignore this because in my professional and personal opinion, this is purely a balonie. (Sorry, I have no reference to the guideline.)

Actually, there are some (superficial) good explanations why you should not use var, but I still think that they are mostly wrong. take the example of "searchabililty": the author claims that the var makes it difficult to search for places where MyType is used. Correctly. So are the interfaces. In fact, why do I want to know where the class is used? I may be more interested in where it will still be searchable, because somewhere its constructor must be called (even if this is done indirectly, the type name is mentioned somewhere). - Conrad Rudolph

-2
source share

All Articles