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?
views:
47answers:
3
+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
2010-07-13 22:10:05
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
2010-07-13 22:15:03
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
2010-07-13 22:16:10