0

所以我有一个字符串,它可能是不同格式的日期。我想创建一种方法,尝试每个方法直到成功,然后返回转换后的日期,或者如果它不匹配任何格式则抛出错误。我写了这个:

private string ConvertDate(string toConvert)
{
    if (string.IsNullOrEmpty(toConvert)) { return ""; }

    DateTime date;
    bool success = DateTime.TryParseExact(toConvert,
            "MMddyy",
            new CultureInfo("en-US"),
            DateTimeStyles.None,
            out date);

    if (!success)
    {
        success = DateTime.TryParseExact(toConvert,
            "MMddyyyy",
                new CultureInfo("en-US"),
            DateTimeStyles.None,
            out date);
    }
    if (!success)
    {
        success = DateTime.TryParseExact(toConvert,
            "MM/dd/yy",
            new CultureInfo("en-US"),
            DateTimeStyles.None,
            out date);
    }
    if (!success)
    {
        success = DateTime.TryParseExact(toConvert,
            "MM/dd/yyyy",
            new CultureInfo("en-US"),
            DateTimeStyles.None,
            out date);
    }
    if (!success) throw new Exception("Date formats are not recognized");

    return date.ToString();
}

它有效,但我觉得写这一切很愚蠢,我认为必须有一种更简单的方法来一次检查许多不同的日期格式。有任何想法吗?

4

2 回答 2

3

这至少更容易维护。尽管函数名称具有误导性。它可能应该类似于 StandardizeDateFormat。

private string ConvertDate(string toConvert)
{
    if (string.IsNullOrEmpty(toConvert)) { return ""; }

    string[] dateFormats = new string[]{"MMddyy","MMddyyyy","MM/dd/yy","MM/dd/yyyy"};
    DateTime date;
    bool success = false;
    for(int i = 0;i<dateFormats.Length &&!success;i++)
    {
        success = DateTime.TryParseExact(toConvert,
        dateFormats[i],
            new CultureInfo("en-US"),
            DateTimeStyles.None,
            out date);
    }
    if (!success) throw new Exception("Date formats are not recognized");

    return date.ToString();
}

编辑:实际上,我可能会像这样进一步简化它

private string ConvertDate(string toConvert)
{
    if (string.IsNullOrEmpty(toConvert)) { return ""; }

    string[] dateFormats = new string[]{"MMddyy","MMddyyyy","MM/dd/yy","MM/dd/yyyy"};
    DateTime date;
    for(int i = 0;i<dateFormats.Length ;i++)
    {
        if(DateTime.TryParseExact(toConvert, dateFormats[i], new CultureInfo("en-US"), DateTimeStyles.None, out date))
            return date.ToString();
    }
    throw new Exception("Date formats are not recognized");
}
于 2012-12-13T21:46:48.640 回答
1

尝试这样的事情。假设MM始终是第一个,年份是2000 or later(对于yy格式)

string date = "10/25/2011";
string[] arr = date.ToArray() 
              .Where(ch => ch > 47 && ch < 58 ) //Filter out all but numbers
              .Select(s => s.ToString()).ToArray(); 

if(arr.Length >5)
{
   string ISOformattedDate = string.Format( arr.Length == 6 ? 
          "{4}{5}-{0}{1}-{2}{3}T00:00:00" : 
          "{4}{5}{6}{7}-{0}{1}-{2}{3}T00:00:00", arr);
   DateTime mydate = Convert.ToDateTime(ISOformattedDate);
}
于 2012-12-13T22:01:12.477 回答