我有产品列表,每个产品都有DateTime类型的创建日期。 我想在我输入字符串类型之后创建一些产品。
我以字符串类型输入EnteredDate ,如下所示: 05/16/2012
1. var dates = from d in Products 2. where d.CreateDate >= DateTime.ParseExact( EnteredDate, "mm/dd/yy", null ) 3. select d;在第二行中,我得到错误,因为字符串未被识别为“mm / dd / yy” 的有效日期时间。 我也尝试过DateTime.Parse(),Convert.ToDateTime()并得到相同的错误。 我如何通过创建日期来过滤此产品列表?
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?
最满意答案
“mm”是分钟,而你的年份是4位数字,而不是2.如果你的格式真的是这样,你想要“MM / dd / yyyy”。 你在这方面有多自信? (特别是,如果它是由用户输入的,你应该让你的代码对文化敏感......)
我建议将解析部分从查询中拉出来,如果你确实有固定的格式,也可能使用不变的文化进行解析:
DateTime date = DateTime.ParseExact(EnteredDate, "MM/dd/yyyy", CultureInfo.InvariantCulture); var dates = Products.Where(d => d.CreateDate >= date);"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);更多推荐
发布评论