无法在天数小于12时以适当的格式获取date从EXCEL在C#

我是新来的C#。 当我试图使用下面的代码导入Excel表:

try { DateTime date = DateTime.FromOADate(w.Cells[i, index[j]].value2); string str = date.ToString("dM-yyyy"); dRow[j] = Convert.ToDateTime(str, ci); } catch (Exception) { try { String ss1 = (String)w.Cells[i, index[j]].value2; if (ss1 == null || ss1.Equals("NIL") || ss1.Equals(".")) { dRow[j] = DBNull.Value; } else if (ss1 != null) { DateTime dat = Convert.ToDateTime(ss1); ss1 = dat.ToString(ci.NumberFormat); dRow[j] = Convert.ToDateTime(ss1,null); } else { dRow[j] = DBNull.Value; } } catch (Exception ex1) { try { String ss2 = (String)w.Cells[i, index[j]].value2; if (ss2 != null) { String ss2_t = ss2.Trim(); DateTime da = DateTime.ParseExact(ss2_t, "dM-yyyy", null); dRow[j] = da; } else { dRow[j] = DBNull.Value; } } catch (Exception ex2) { try { String ss3 = (String)w.Cells[i, index[j]].value2; if (ss3 != null) { String ss3_t = ss3.Trim(); DateTime da1 = DateTime.ParseExact(ss3, "dM-yyyy", CultureInfo.InvariantCulture); dRow[j] = da1; } else { dRow[j] = DBNull.Value; } } catch (Exception) { dRow[j] = DBNull.Value; } } } 

一切工作正常,直到date的date值小于12.例如,如果DATE是23-07-2013它工作正常。 但如果DATE是7-5-2013,那么DateTime.FromOADate()会将其转换为2013年7月5日。 我完全卡住了。 请尽快帮助我。

如果你的意思是你的strvariables的困难,那么使用这种格式:

 string str = date.ToString("dd-mm-yyyy"); 

更新

传递给DateTime.FromOADate()的参数是一个明显不是格式敏感的double。 所以我不确定为什么你需要把它转换成一个string,然后回到date。 是否有可能dRow[j] = date是你所需要的?

如果FromOADate()的返回值不正确,那么您需要返回到您的源数据,即Excel。 您需要在那里调整格式设置,或者,如果导入的数据是运行一个小的VBAmacros来自己转换值。

我不确定在代码中你看到了“dM-yyyy”v。“Md-yyy”区别。 如果你正在看你的dRow[j]variables,那么这将遵守你定义的CultureInfo ,大概是civariables。

下面是一些代码,显示了pipe理datestring转换的三种方式,前两种操作CultureInfo ,第三种是纯手工stringparsing。

有一个戏看看这些是否符合你的需求,但我仍然回到我原来的问题“你需要去'date – string – date'在所有”?

 DateTime date = DateTime.FromOADate(42491); string str = date.ToString("dM-yyyy"); Console.WriteLine(str); //CultureInfos CultureInfo ciGB = new CultureInfo("en-GB", false); CultureInfo ciUS = new CultureInfo("en-US", false); //ToDateTime version DateTime dateGB = Convert.ToDateTime(str, ciGB); DateTime dateUS = Convert.ToDateTime(str, ciUS); Console.WriteLine("ToDateTime: GB = {0}, US = {1}", dateGB, dateUS); //ParseExact version DateTime parsedGB = DateTime.ParseExact(str,"dM-yyyy", ciGB); DateTime parsedUS = DateTime.ParseExact(str, "Md-yyyy", ciUS); Console.WriteLine("ParseExact: GB = {0}, US = {1}", parsedGB, parsedUS); //Manual parsing var parts = str.Split('-'); int item1 = int.Parse(parts[0]); int item2 = int.Parse(parts[1]); int item3 = int.Parse(parts[2]); DateTime manualGB = new DateTime(item3, item2, item1); DateTime manualUS = new DateTime(item3, item1, item2); Console.WriteLine("Manual: GB = {0}, US = {1}", manualGB, manualUS);