2010-07-13 49 views
3

在我的C#數據訪問層...我從Excel中檢索數據集...並且有一個十進制excel字段,其格式爲:20090701返回日期。我需要將其轉換爲C#DateTime。什麼是最好的方式來做到這一點?Excel十進制格式到C#日期時間

回答

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

ParseExact方法允許您指定的日期/時間要轉換的格式字符串。在你的情況下:四位數年份,然後是兩位數月份,然後是兩位數字的一個月份。

0

我會做這樣的事情,如果你想在應用範圍內實現它。

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); 
0

這是一個不太直觀的答案。

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