Jeyhun Rahimov
Jeyhun Rahimov

Reputation: 3787

How to parse string to DateTime?

I have product list and every product has create date in DateTime type. I want to take some products that created after my entering time in string type.

I enter EnteredDate in string type, like this format : 05/16/2012

1.    var dates = from d in Products
2.                where d.CreateDate >= DateTime.ParseExact( EnteredDate, "mm/dd/yy", null )
3.                select d;

In second line I got error as String was not recognized as a valid DateTime for "mm/dd/yy". I also tried DateTime.Parse(), Convert.ToDateTime() and got same error. How can I filter this product list by create date?

Upvotes: 1

Views: 2435

Answers (2)

Krešimir Lukin
Krešimir Lukin

Reputation: 399

Call

DateTime.ParseExact(EnteredDate, "MM/dd/yyyy", CultureInfo.InvariantCulture); 

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1499770

"mm" is minutes, and your year is 4 digits, not 2. You want "MM/dd/yyyy", if your format is really always that. How confident are you on that front? (In particular, if it's entered by a user, you should probably make your code culture-sensitive...)

I would suggest pulling the parsing part out of the query though, and also probably using the invariant culture for parsing if you've really got a fixed format:

DateTime date = DateTime.ParseExact(EnteredDate, "MM/dd/yyyy",
                                    CultureInfo.InvariantCulture);

var dates = Products.Where(d => d.CreateDate >= date);

Upvotes: 5

Related Questions