如何检查C#中yyyyMMddHHmmss格式的字符串?

时间:2019-03-12 10:25:05

标签: c#

我想检查C#中的字符串是否为yyyyMMddHHmmss格式。最好的方法是什么。

这里我尝试使用DateTime.TryParse,但是它总是返回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
{
}

注意:有时timestampValue可能包含普通文本而不是时间戳记值。

3 个答案:

答案 0 :(得分:2)

TryParse没有过载可以提供准确的格式,请尝试使用TryParseExact。示例:

// adjust IFormatProvider and DateTimeStyles if needed
if (DateTime.TryParseExact(
    timestampValue, 
    "yyyyMMddHHmmss", //format
    CultureInfo.CurrentCulture, 
    DateTimeStyles.None, out outDate))
{
    //do work
}

答案 1 :(得分:2)

使用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://docs.microsoft.com/en-us/dotnet/api/system.datetime.tryparseexact?view=netframework-4.7.2

答案 2 :(得分:0)

我希望这段代码对您有帮助

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;
        }