Excel decimal table format in C # DateTime

In my C # Data Access Layer ... I remove the dataset from Excel ... excel and have a decimal field that returns the date in the following format: 20090701. I need to convert this to C # DateTime. What is the best way to do this?

+3
source share
3 answers
DateTime.ParseExact( value.ToString(), "yyyymmdd" );

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

+4
source

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

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
source

And a less intuitive answer for a 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
source

Source: https://habr.com/ru/post/1754514/


All Articles