How to find the difference between two dates
How can 开发者_运维百科I find the difference between two dates. For example, the difference between a birthdate and the current date. Both dates would be in text boxes.
I'll simply assume a text box named BirthdateTextBox exists and contains your birth date:
DateTime birthDate = DateTime.Parse(BirthdateTextBox.Text);
TimeSpan timeBetweenDates = DateTime.Now.Subtract(birthDate);
There are also some overloads of DateTime.Parse, as well as DateTime.TryParse, that you should read about in the documentation.
Convert the string obtained from text box to
DateTime
format.DateTime dt1 = Convert.ToDateTime(textBoxStringOne);
DateTime dt2 = Convert.ToDateTime(textBoxStringTwo);
Compute the difference
System.TimeSpan difference = dt1.Subtract(d2); // Assuming dt1 > dt2
Hope, this should give you an idea.
look into the DateTime
class, it supports subtracting two dates, which will result in a TimeSpan
.
You can create a DateTime
object from a string by using its Parse()
or ParseExact()
methods, there are plenty of examples on how to use these here on SO or on msdn - it depends on the format of your time string.
You can use
DATEDIFF (datepart ,startdate ,enddate )
1.datepart- difference in yr,month 2. startDate 3. enddate
2 and 3 are DateTime objects
DateTime.Now will get currentDate
Read more for DateDiff()
精彩评论