Validate Date of form dd / MM / yyyy hh: mm in c #?

0

I am trying to validate a date of the form dd / MM / yyyy hh: mm but in doing so with the code below, I would validate any correct date format.

           try
            {
                DateTime.Parse(Fecha);
                FechaError = 0;
            }
            catch
            {
                FechaError = 2;
            }
    
asked by Acd 18.06.2017 в 18:42
source

2 answers

3

You can use the DateTime.ParseExact function, which throws an exception if there is an error:

var dateTime = DateTime.ParseExact("30/01/2017 03:45","dd/MM/yyyy HH:mm",CultureInfo.InvariantCulture);

You can also check the function DateTime.TryParseExact

DateTime fecha;

if (DateTime.TryParseExact("30/01/2017 03:45", "dd/MM/yyyy HH:mm", null, System.Globalization.DateTimeStyles.None, out fecha)
{
    Console.WriteLine(fecha);
}
else
{
    Console.WriteLine("Fecha invalida"); 
}
    
answered by 18.06.2017 / 20:49
source
1

Let's see if I understood ... Do you try to validate a date only using the format: "dd / MM / yyyy hh: mm"? For example, if you wrote "07/15/1992 11:23" this date would be accepted and validation would pass. Same thing that should not happen if I write something like "11:23 p.m. 15-7-92" (Even though the DateTime.Parse conversion of this last date will be done successfully)

If I understood your question correctly, maybe you can solve the problem with the following code:

        string Fecha = "Alguna fecha cualquiera";
        int FechaError = 0;
        DateTime FechaValida = new DateTime();

        try
        {
            FechaValida = DateTime.Parse(Fecha);
            if (FechaValida.ToString("dd/MM/yyyy hh:mm") == Fecha)
                FechaError = 0;
            else
            {
                FechaValida = new DateTime();
                FechaError = 2;
            }
        }
        catch
        {
            FechaError = 2;
        }

By the way ... this code will only validate DateTime variables whose time is 12:00 a. m. - 11:59 a. m. unless you change the acceptance format to: "dd / MM / yyyy hh: mm tt" or "dd / MM / yyyy HH: mm"

    
answered by 18.06.2017 в 20:11