views:

47

answers:

3

In my C# Data Access Layer...I am retrieving a dataset from Excel ...and there is a decimal excel field which returns date in the format : 20090701. I need this to be converted to C# DateTime. What is the best way to do it?

+3  A: 
DateTime.ParseExact( value.ToString(), "yyyymmdd" );

The ParseExact method allows you to specify the format string for the date/time you are converting. In your case: a four digit year, then two digit month, then two digit day of month.

LBushkin
A: 

I would do something like this if you want to implement it application wide.

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);
Biff MaGriff
A: 

And a less intuitive answer for good measure.

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