I’m not sure why my head is spinning right now – long day for sure – but I need some help with this one.
I have a DateTime variable and a String variable. I ultimately need to compare the two for equality. The DateTime will either be null or a DateTime. The string will either be a date represented as a string (mm/dd/yy) or a single word. A simple bool indicating the two variables are equal is all I need but I’m really struggling with this.
At the moment, I get an error that says date2 is uninitialized. Suggestions are much appreciated. Thanks!
Here is what I started with…
string date1= "12/31/2010";
DateTime? date2= new DateTime(1990, 6, 1);
bool datesMatch = false;
DateTime outDate1;
DateTime.TryParse(date1, out outDate1);
DateTime outDate2;
if (date2.HasValue)
{
DateTime.TryParse(date2.Value.ToShortDateString(), out outDate2);
}
if (outDate1== outDate2)
{
datesMatch = true;
}
if (!datesMatch)
{
// do stuff here;
}
FYI – date1 and date2 are initialized at the top for dev purposes only. The actual values are pulled from a database.
EDIT #1 – Here is my latest. How do I get rid of the error caused by outDate2 not being initialized? I placed an arbitrary date in there and it clears the error. It just feels wrong.
string date1 = "12/31/2010";
DateTime? date2 = new DateTime(1990, 6, 1);
bool datesMatch = false;
DateTime outDate1;
bool successDate1 = DateTime.TryParse(date1, out outDate1);
DateTime outDate2;
bool successDate2 = false;
if (date2.HasValue)
{
successDate2 = DateTime.TryParse(date2.Value.ToShortDateString(), out outDate2);
}
if (successDate1 && successDate2)
{
if (outDate1 == outDate2)
{
datesMatch = true;
}
}
if (!datesMatch)
{
// do stuff here;
}
DateTime.TryParsereturns a boolean, so you know whether or not it succeeded. Use that return value.