Hunar
Hunar

Reputation: 399

find difference between two date textboxes

in my c# form i have two date text boxes on for borrow date and the other for return date

borrowed_date_txt , return_date_txt

i want to compare two text boxes to find difference between them and if the date of borrowed_date_txt is greater than the date of return_date_txt i want to make the return_date_txt background red?

Upvotes: 1

Views: 2974

Answers (4)

Jim T
Jim T

Reputation: 131

Something like this should work for you.

System.TimeSpan = EndDate.Subtract(StartDate)

gives you the difference in days-hours-seconds-milliseconds. If you just want the difference in the # of days, you can specify that by using the Days property of the System.TimeSpan class.

DateTime StartDate;
DateTime EndDate;
TimeSpan Difference;

StartDate = Convert.ToDateTime(txtStartDate.Text.ToString());
EndDate = Convert.ToDateTime(txtEndDate.Text.ToString());

Difference = EndDate.Subtract(StartDate);

lblDifference.Text = Convert.ToString(Difference.Days);

Upvotes: 0

selkathguy
selkathguy

Reputation: 1171

Parse them to DateTimes and TimeSpans and do your logic/comparisons with these. Then call ToString() in the result and you will get a default-formatted date and time. DateTime also provides very handy properties based on the dates.

See: http://msdn.microsoft.com/en-us/library/system.datetime(v=vs.110).aspx

EDIT: I am assuming this is a Windows Form and not a web form. I will revise if web is what you need.

Upvotes: 2

Charls
Charls

Reputation: 319

You can use DateTime.Compare

int idiff = DateTime.Compare(DateTime.Parse(borrowed_date_txt), DateTime.Parse(return_date_txt));
if (idiff > 0) //borrowed_date_txt is greater than the date of return_date_txt 
{
//Do what you need    
}

Upvotes: 1

i100
i100

Reputation: 4666

you should convert string to date then you could try this:

DateTime date1 = Convert.ToDateTime(borrowed_date_txt);
      DateTime date2 = Convert.ToDateTime(return_date_txt);
      int result = DateTime.Compare(date1, date2);
      string relationship;

      if (result < 0)
         relationship = "is earlier than";
      else if (result == 0)
         relationship = "is the same time as";         
      else
         relationship = "is later than";

Upvotes: 0

Related Questions