Dates in C# 2005 - Comparison and Conversion

jcrcarmo

Freshman
Joined
Dec 14, 2005
Messages
32
Hi folks,

I'm having trouble converting text to date and comparing them. Is there a similar to VB.Net's IsDate in C# 2005? Please check out the code below and see if you can find what's wrong. Yeah, I know, I'm a newbie... :) The code in red is where I'm getting the error messages:


--------------------------------------------------------------------------

1) Checking if the text of a TextBox is date:

if IsDate(this.Date1TextBox.Text)
{

}

--------------------------------------------------------------------------

2) Converting and comparing the dates of two TextBoxes:

if (Convert.ChangeType(this.Date1TextBox.Text, DateTime) > Convert.ChangeType(this.Date2TextBox.Text, DateTime))
{

}

--------------------------------------------------------------------------

Thanks a lot,

JC :)
 
jcrcarmo said:
1) Checking if the text of a TextBox is date:

if IsDate(this.Date1TextBox.Text)
{

}
One method for doing this is something along the lines of...
C#:
		public bool IsDate(object inValue)
		{
			bool bValid;

			try 
			{
				DateTime myDT = DateTime.Parse(inValue);
				bValid = true;
			}
			catch (FormatException e) 
			{
				bValid = false;
			}

			return bValid;
		}
jcrcarmo said:
2) Converting and comparing the dates of two TextBoxes:

if (Convert.ChangeType(this.Date1TextBox.Text, DateTime) > Convert.ChangeType(this.Date2TextBox.Text, DateTime))
{

}

That throws an error because the overload requires a type and your passing it an object. You could change the DateTime to typeof(DateTime), don't know if that would help though I haven't tried it.
 
Mmmmm.... code....
C#:
/* TryParse tries to parse a string. If it succeeds, it stores
 * the date in the OUT variable and returns true. If it fails, it
 * returns false. 
 */
if(DateTime.TryParse(MyDateString, out MyDate)) {
	// > and < operators are overloaded.
	if(MyDate > DateTime.Now) {
		// It's the future!
	}
}

P.S. Not to rag on you, Cags, but I would personally discourage using code like the code you posted:
C#:
		public bool IsDate(object inValue)
		{
			bool bValid;
 
			try 
			{
				DateTime myDT = DateTime.Parse(inValue);
				bValid = true;
			}
			catch (FormatException e) 
			{
				bValid = false;
			}
 
			return bValid;
		}
It essentially depends on exception handling for validation, and exception handling is specifically not intended to be used for program flow control, but rather for "exceptional circumstances" (and that's not exceptional in a good way, either).
 
Last edited:
Hi Cags, I tried your suggestion, but unfortunately it didn't work. Thanks for the quick reply anyway! Bye for now, JC :)
 
Back
Top