2

我有一个执行邮件合并和其他操作的 VSTO 应用程序。

邮件合并数据库是一个 Excel 数据库,其中一些DateTime字段存储为 (dd/MM/YYYY)(例如 29/04/2012)。我的问题是在 Excel 中日期看起来不错,但在 Word 中它以其他格式显示(MM/dd/yyyy)(例如 2012 年 4 月 29 日)。当尝试在我的 VSTO 应用程序上获取此日期时,它会引发转换错误,指示字符串的格式错误。

所有这些都发生在同一台机器上。如果我将 VSTO 中的文化信息更改为 en-US,它可以正常工作。

// This way fails 
edictoActual.FechaEdicto = Convert.ToDateTime(fields(fieldFechaEdicto).value); 

// This way Works
IFormatProvider Formato = new System.Globalization.CultureInfo("en-US", true);
edictoActual.FechaEdicto = Convert.ToDateTime(fields(fieldFechaEdicto).value,Formato); 

为什么会这样?

4

1 回答 1

2
string DateString = "29/04/2012"; //DateString needs to be replaced with your fields value as a string
var dateLength = DateString.Length;
IFormatProvider culture = new CultureInfo("en-US", true);
DateTime dateVal;
switch (dateLength)
{
     case 8:
        {
          dateVal = DateTime.ParseExact(DateString, "M/d/yyyy", culture);
            break;
        }
    case 9:
        {
            // he you can add your own additional if(){} condition to check if date value Day has a length of 2 
            // if so then you know that the date is in m/dd/yyyy format
            // otherwise you know it's in mm/d/yyyy but 
            dateVal = DateTime.ParseExact(DateString, "M/dd/yyyy", culture);
            break;
        }
    case 10:
        {
            dateVal = DateTime.ParseExact(DateString, "MM/dd/yyyy", culture);
            //or change the above to look like the following 
            //dateVal = DateTime.ParseExact(DateString, "dd/MM/yyyy", culture);
            break;
        }

}
于 2013-02-21T16:16:06.957 回答