Dates in C# 2005 - Comparison and Conversion

jcrcarmo

Active member
Joined
Dec 14, 2005
Messages
32
Hi folks,

Im having trouble converting text to date and comparing them. Is there a similar to VB.Nets IsDate in C# 2005? Please check out the code below and see if you can find whats wrong. Yeah, I know, Im a newbie... :) The code in red is where Im 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), dont know if that would help though I havent 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) {
		// Its 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 thats not exceptional in a good way, either).
 
Last edited by a moderator:
Hi Cags, I tried your suggestion, but unfortunately it didnt work. Thanks for the quick reply anyway! Bye for now, JC :)
 
Back
Top