Check if a date is valid

Asked

Viewed 9,343 times

0

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

How can I verify that this date is valid?

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

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

NOTE: I cannot use the classes Datetime and Timespan.

  • Why can’t you use the Datetime classes? Is this a matter of proof, or homework? The way you want to check the validity of a date is very bad. The ideal is to use DateTime.ParseExact() and set the date shape. What you are doing is not checking if the date is invalid, since you will accept 55/44/0001 34:68 as a valid date... Although the GOKU response is a regexp that can almost catch all scenarios...

  • Why can’t you use these classes? That doesn’t make any sense. If you want to do something wrong you would need a justification.

  • Since when is validating a date without using a "ready" form wrong? I do not understand why creating my validation method is wrong... and, yes, it is a matter for educational means.

  • @Jonathanbarcela is very complex validate a date, do not just look if you have the correct digits there, there are several situations that will give wrong result doing so. You can learn to validate by hand, just not the wrong way. If your question was clearer and had not accepted a very naive answer I would understand that you want to learn how it is done internally, but ended up getting a bad way and a lot of people will read it and find that this is good and will have failed systems. Take a look at the complexity:

  • https://referencesource.microsoft.com/#mscorlib/system/globalization/datetimeparse.Cs,f75289affb7e0ce3

  • @bigown, the answer may be naive, but it’s within what he’s setting.. I can’t use the Datetime and Timespan classes.

  • @Gokussjgod the problem is the question itself, it is not helping anyone and if it did not have the alert to people here many people would copy it as if it were something valid. Pity there are people who will not read the comments and will make the mistake of trying to validate naively.

  • @bigown, don’t be so. edited the answer.

  • @Jonathanbarcela, if specified face-first that this is a question for educational purposes, probably this whole discussion would be irrelevant. It turns out that using in alternative ways (e.g. regex) is wrong in a system productive because the "ready" form was thoroughly tested before being released into the framework.

  • (Nothing against your answer, @Gokussjgod ;) )

  • 1

    In question I say exactly what I want: A validação seria só para ver se não existem letras dentre os números e/ou símbolos que em lugares errados, como por exemplo: 0//03/2010 23::0. I don’t need more validations, that’s for my case, but I haven’t found a better way to describe it.

Show 6 more comments

3 answers

3


How can you not use the DateTime an exit would be as follows 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]$

Look in the dotnetfiddle.

But the ideal would be for you to use the Tryparseexact, ensuring that you would actually have a correct date.

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

See what has happened in that question to get an idea.

1

Assuming the date is always received in the format dd/mm/yyyy hh:mm, 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

0

public static class ValidarData
{
    public static bool DataCompleta(string data)
    {
        Regex ok = new Regex(@"(\d{2}\/\d{2}\/\d{4} \d{2}:\d{2})");
        return ok.Match(data).Success;
    }
    public static bool DataPura(string data)
    {
        Regex ok = new Regex(@"(\d{2}\/\d{2}\/\d{4})");
        return ok.Match(data).Success;
    }
}

To use do :

string Texto = "31/03/2021";
bool Dataok = ValidarData.DataPura(Texto); 

or

string Texto = "31/03/2021:14.30";
bool Dataok = ValidarData.DataCompleta(Texto); 

Browser other questions tagged

You are not signed in. Login or sign up in order to post.