tags:

views:

323

answers:

2

I have the following date as string "091020". I am using SubSonic as my DAL. When I do

myObject.DateColumn = "091020"

I get the error "Conversion from type String to Type Date is not valid"

I tried playing with the IFormatProvider and CultureInfo but can't seem to get raid of the error.

What am I missing?

+3  A: 

Try

myObject.DateColumn = DateTime.ParseExact("091020", "yyMMdd", null)

DateTime.ParseExact lets you specify exactly how to parse the date when it's not entirely obvious.

David Stratton
I tried this earlier but got the error Unable to cast object of type 'System.String' to type 'System.IFormatProvider
Saif Khan
Got it! I was using DateTime.Parse
Saif Khan
If I have the time as "1422" can I use DateTime.ParseExact to store the time in a System.Date object?
Saif Khan
I believe so, but then the date defaults to DateTime.MinValue, which is, I believe, 1/1/0001 (January first, 1 A.D.)
David Stratton
The trick, then is to DISPLAY only the time portion. The easiest way to do this is by using DateTime.ToString("hh:mm:ss")
David Stratton
+2  A: 

.Net can't parse that into a valid date. Throw this in a new project and verify that:

string sDate = "091120";
DateTime dt = DateTime.MinValue;

if (DateTime.TryParse(sDate, out dt))
    MessageBox.Show(dt.ToShortDateString());
else
    MessageBox.Show("Nope");

So, if you KNOW that all your dates are yyMMdd, then use this:

DateTime.ParseExact("091120", "yyMMdd", null)

How are you getting these dates? Are they guaranteed to be 6 digits in the yyMMdd format?

Matt Dawdy