0

I want to check if a string is in yyyyMMddHHmmss format in C#. What is the best way to do it.

Here I have tried with DateTime.TryParse, but it always return false.

string currentFileName = "Test_File_20190312122838";
string timestampValue = currentFileName.Substring(currentFileName.LastIndexOf('_')+ 1);
DateTime outDate = DateTime.Now;

if (DateTime.TryParse(timestampValue, out outDate)) // always return false
{
}

Note: Sometimes timestampValue may contain normal text instead of a timestamp value.

Aria
  • 3,724
  • 1
  • 20
  • 51
SUBHAJIT GANGULI
  • 361
  • 6
  • 10

3 Answers3

2

TryParse doesn't have overload to provide exact format, try using TryParseExact. Example:

// adjust IFormatProvider and DateTimeStyles if needed
if (DateTime.TryParseExact(
    timestampValue, 
    "yyyyMMddHHmmss", //format
    CultureInfo.CurrentCulture, 
    DateTimeStyles.None, out outDate))
{
    //do work
}
Johnny
  • 8,939
  • 2
  • 28
  • 33
2

Use TryParseExact

string currentFileName = "Test_File_20190312122838";
string timestampValue = currentFileName.Split('_')[2]; 
// if your naming convention is not always the same, you may want to leave the resolving of the timestampvalue as you did
// string timestampValue = currentFileName.Substring(currentFileName.LastIndexOf('_')+ 1);

DateTime outDate = DateTime.Now;

if (DateTime.TryParseExact(timestampValue, "yyyyMMddHHmmss", 
    CultureInfo.CurrentCulture, System.Globalization.DateTimeStyles.None, out outDate))
{
    // whatever you want to do...
}

https://learn.microsoft.com/en-us/dotnet/api/system.datetime.tryparseexact?view=netframework-4.7.2

blfuentes
  • 2,731
  • 5
  • 44
  • 72
0

I hope this piece of code may help you

public static bool IsValidDateTime(string dateTime)
        {
            long lCheck;
            dateTime = dateTime.Trim();
            //check if its valid integers
            bool status = long.TryParse(dateTime, out lCheck);
            //if its not valid long value or length does not conforms the format throw an exception or return false
            if (!status || dateTime.Length != 14)
                throw new Exception("Input does not conforms yyyyMMddHHmmss fromat");

            try
            {

                    DateTime.ParseExact(dateTime.ToString(), "yyyyMMddHHmmss", System.Globalization.CultureInfo.InvariantCulture);
            }
            catch (Exception exp)
            {
                return false;
            }

            //everything is well lets return true
            return true;
        }