Compare if two date fields are the same in C #

1

I have form and in this form I have two date fields, campodata1 is populated by user and campodata2 is filled by the database, now I need a code to compare if these two fields have the same information.

The fields are string I'm even using in form the masktext for date fields, I just need to compare to see if they are the same to do an action.

Follow an image of my form

    
asked by anonymous 07.03.2018 / 13:38

3 answers

-1

What you can do is simply convert the dates in STRING format to DATETIME and make a normal comparison:

DateTime data1 = Convert.ToDateTime(CampoData1.text);
DateTime data2 = Convert.ToDateTime(CampoData2.text);

if (data1 > data2)
{
    /*...*/
}
else if (data1 == data2)
{
    /*...*/
}
else if (data1 < data2)
{
    /*...*/
}
    
07.03.2018 / 14:21
2
using System;

public class Example
{
   public static void Main()
   {
      DateTime date1 = new DateTime(2009, 8, 1, 0, 0, 0);
      DateTime date2 = new DateTime(2009, 8, 1, 12, 0, 0);
      int result = DateTime.Compare(date1, date2);
      string relationship;

      if (result < 0)
         relationship = "é mais nova que";
      else if (result == 0)
         relationship = "é igual a";         
      else
         relationship = "é depois de";

      Console.WriteLine("{0} {1} {2}", date1, relationship, date2);
   }
}

Source: link

    
07.03.2018 / 13:42
2

The accepted solution will break the application whenever someone enters a wrong format, so it works:

if (!datetime.TryParse(CampoData1.text, out var data1)) //faz o tratamento de erro aqui
if (!datetime.TryParse(CampoData2.text, out var data2)) //faz o tratamento de erro aqui
//só pode ir pra frente aqui se não houve erro acima
if (data1 > data2) //faz algo para o maior
else if (data1 < data2) //faz algo para o menor
else //faz algo para o igual
    
07.03.2018 / 16:59