Excel十进制格式到C#DateTime

在我的C#数据访问层…我从Excel中检索数据集…有一个十进制Excel字段返回date格式: 20090701 。 我需要将其转换为C# DateTime 。 什么是最好的办法呢?

 DateTime.ParseExact( value.ToString(), "yyyymmdd" ); 

ParseExact方法允许您为正在转换的date/时间指定格式string。 在你的情况下:一个四位数字的年份,然后是两位数字的月份,然后是两位数字的月份。

如果你想在应用程序范围内实现,我会做这样的事情。

 System.Globalization.CultureInfo cultureInfo = new System.Globalization.CultureInfo("en-CA"); // Defining various date and time formats. dateTimeInfo.LongDatePattern = "yyyyMMdd"; dateTimeInfo.ShortDatePattern = "yyyyMMdd"; dateTimeInfo.FullDateTimePattern = "yyyyMMdd"; // Setting application wide date time format. cultureInfo.DateTimeFormat = dateTimeInfo; // Assigning our custom Culture to the application. //Application.CurrentCulture = cultureInfo; Thread.CurrentThread.CurrentCulture = cultureInfo; Thread.CurrentThread.CurrentUICulture = cultureInfo; DateTime.Parse(excelDate); 

而一个不太直观的答案是好的措施。

 var a = 20090701m; var b = a / 10000; var year = (int)b; var c = (b - year) * 100; var month = (int)c; var day = (int)((c - month) * 100); var dt = new DateTime(year, month, day);