Help On @ Dates Comparision

Posted by Vijayar under C# on 12/22/2011 | Points: 10 | Views : 893 | Status : [Member] | Replies : 2
HI
I need to compare 2 date time fields and assign value to a field
how to do this
if txtdate1>txtdate2
fee=25
else
fee=10

I select dates using calendar

vijaya


Responses

Posted by: Sksingh on: 12/22/2011 [Member] Starter | Points: 25

Up
0
Down
Hi,

Try below code :
 DateTime date1 = new DateTime(2009, 8, 1, 12, 0, 1);

DateTime date2 = new DateTime(2009, 8, 1, 12, 0, 0);
int result = DateTime.Compare(date1, date2);
string val;

if (result < 0)
val = "is less than";
else if (result == 0)
val = "is the same time as";
else
val = "is greater than";
Console.WriteLine("{0} {1} {2}", date1, val, date2);
OR

You can check the condition like below also.
if (DateTime.Compare(date1, date2) < 0)
{
Console.WriteLine("second date is larger than the first date");
}
else if (DateTime.Compare(date1, date2) == 0)
{
Console.WriteLine("second date is same as first date");
}
else
{
Console.WriteLine("second date is smaller than the first date");
}


Instead of date1 and date2 you can use calender value.



Regards,
Sunil

Vijayar, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Rsmc2011 on: 12/26/2011 [Member] Starter | Points: 25

Up
0
Down
Suppose we have two TextBox Which Id's are txtStartDate and txtEndDate

string frmdt = txtStartDate.Text;
string todt = txtEndDate.Text;
FromDate=string.empty;
ToDate =string.empty;
int Datediff = 0;
int diff = 0;
//For this use the namespace System.Globalization;
FromDate = Convert.ToDateTime(frmdt, c).ToString("dd-MMM-yyyy", DateTimeFormatInfo.InvariantInfo);
ToDate = Convert.ToDateTime(todt, c).ToString("dd-MMM-yyyy", DateTimeFormatInfo.InvariantInfo);

//your answer in start here

//Code for date difference
DateTime dt2 = Convert.ToDateTime(ToDate);
DateTime dt1 = Convert.ToDateTime(FromDate);

Datediff = DateTime.Compare(dt1, dt2);
TimeSpan diff1 = dt2.Subtract(dt1);
diff = Convert.ToInt32(diff1.Days);

if(diff<=100)
respsoe.write("hellow");

Chandresh

Vijayar, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response