如何转换不同格式的日期

时间:2012-12-13 21:25:44

标签: c# date date-format

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

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

它有效,但我觉得写这些都很傻,我认为必须有一种更简单的方法来检查1遍中的许多不同的日期格式。有什么想法吗?

2 个答案:

答案 0 :(得分: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");
}

答案 1 :(得分: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);
}