代码之家  ›  专栏  ›  技术社区  ›  E.Rawrdríguez.Ophanim

检查字符串是否为特定的日期格式

  •  0
  • E.Rawrdríguez.Ophanim  · 技术社区  · 8 年前

    嗨,我收到一个日期格式的字符串 每天 ,但我想将其与格式进行比较 年-月-日 如果不一样,当然不一样,我想转换它,对我来说问题是不转换,而是比较两种格式… 所以我想可能是这样的

    var dt = obj.date; //this a string
    
    if (dt.formatDateorsomethingIguess == "dd/MM/yyyy") //this is the part I'm asking for
    {
         usedt(dt);
    } 
    else 
    {
        DateTime dt_format = DateTime.ParseExact(dt.Trim(), "dd-MM-yyyy",
        System.Globalization.CultureInfo.InvariantCulture);
        usedt(dt_format);
    }
    
    2 回复  |  直到 8 年前
        1
  •  1
  •   John Wu    8 年前

    你可以打几个电话来解决这个问题 TryParseExact 以下内容:

    public static DateTime ParseDate(string input)
    {
        DateTime result;
    
        if (DateTime.TryParseExact(input, "yyyy-MM-dd", CultureInfo.CurrentCulture, DateTimeStyles.None, out result)) return result;
        if (DateTime.TryParseExact(input, "dd-MM-yyyy", CultureInfo.CurrentCulture, DateTimeStyles.None, out result)) return result;
    
        throw new FormatException();
    }
    

    快速测试一下:

    public static void Main()
    {
        string[] tests = new string[] { "2018-06-29", "29-06-2018","Invalid" };
    
        foreach (var t in tests)
        {
            var result = ParseDate(t);
            Console.WriteLine( "Year: {0}  Month: {1}  Day: {2}", result.Year, result.Month, result.Day );
        }
    }
    

    输出:

    Year: 2018  Month: 6  Day: 29
    Year: 2018  Month: 6  Day: 29
    Run-time exception (line 18): One of the identified items was in an invalid format.
    

    Sample code on DotNetFiddle

        2
  •  1
  •   Gabriel Bur    8 年前

    你有没有试过看到类似正则表达式的东西?

    我找到了这个([1-2][0-9])([1-9])(3[0-1])/(1[0-2])([1-9])/[0-9]4

    与1995年3月21日匹配

    推荐文章