How to check if a date matches the correct format, i.e. Yyyy-mmm-dd?

I get data from a service call and want to make sure the string is in the correct date format, for example:

2015-Nov-19

I tried using the parsing function with the format yyyy-mmm-dd, but also gives dates like 2015-11-19. What should I do?

+4
source share
6 answers

Use DateTime.TryParseExact

DateTime dt;
string[] formats = { "yyyy-MMM-dd"};
if (!DateTime.TryParseExact(dateValue, formats, 
                System.Globalization.CultureInfo.InvariantCulture,
                DateTimeStyles.None, out dt))
{
    //your condition fail code goes here
    return false;
}
else
{
    //success code
}
+2
source

You need to use a MMMspecifier instead of MMMwith English culture, for example InvariantCulture. None MMMas a custom date and time specifier.

, DateTime.TryParseExact , string[] , .

string s = "2015-Nov-19"; // or 2015-11-19
DateTime dt;
string[] formats = {"yyyy-MMM-dd", "yyyy-MM-dd"};
if(DateTime.TryParseExact(s, formats, CultureInfo.InvariantCulture,
                          DateTimeStyles.None, out dt))
{
    // Successfully parse
}

MM , , M.

+9
+2

. , , . , .

  • .
  • , .
+1

:

DateTime dt = DateTime.Now;

Console.WriteLine(dt.ToString("yyyy-MMM-dd HH:SS"));

. , , DateTime. DateTime.

+1

:

        string stringdate = "2015-Nov-19";

        DateTime date = Convert.ToDateTime(stringdate);

        string tempdate = date.ToString("yyyy-MMM-dd");

        if (tempdate == stringdate)
        {
            // Successfully parsed string goes here 
        }

, , . 2015-11-19, .

0

Source: https://habr.com/ru/post/1616574/


All Articles