开发者

Excel decimal format to C# DateTime

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?


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.


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜