Check if a date is valid

0

I'm getting a date in the format: string: "01/03/2010 23:00"

How can I verify that this date is valid?

By validate, disregard questions of days or months having wrong numbers. The validation would only be to see if there are no letters among the numbers and / or symbols that in the wrong places, for example: 0 // 03/2010 23 :: 0

Is there any way I can do a "full" validation or do I need to separate the elements of the date and check them one by one?

I can not use the DateTime and TimeSpan classes.

    
asked by anonymous 26.10.2016 / 16:17

2 answers

3

As you can not use DateTime an output would be the following regex to do this.

  

^ ([1-9] | ([012] [0-9]) | (3 [01])) / ([0] {0,1} [1-9] | 1 [012]) / \ d \ d \ d \ d   [012] {0,1} [0-9]: [0-6] [0-9] $

See dotnetfiddle.

But ideally you should use TryParseExact , ensuring that you would really have a correct date.

DateTime valor;
var convertido = DateTime
    .TryParseExact(entrada.Conteudo,
                    "dd/MM/yyyy",
                    CultureInfo.InvariantCulture,
                    DateTimeStyles.None,
                    out valor);

See what happened on this question to get an idea.

    
26.10.2016 / 16:32
1

Assuming the date is always received in dd/mm/yyyy hh:mm format, you can use the expression \d{2}\/\d{2}\/\d{4} \d{2}:\d{2} to validate, see an example:

using System;
using System.Text.RegularExpressions;

public class Test
{
    public static bool validarData(string data)
    {
        Regex r = new Regex(@"(\d{2}\/\d{2}\/\d{4} \d{2}:\d{2})");
        return r.Match(data).Success;
    }

    public static void Main()
    {
        Console.WriteLine(validarData("01/03/2010 23:00"));
        Console.WriteLine(validarData("0//03/2010 23::0"));
    }
}

See DEMO

    
26.10.2016 / 16:48