简体   繁体   English

如何将字符串解析为DateTime?

[英]How to parse string to DateTime?

I have product list and every product has create date in DateTime type. 我有产品列表,每个产品都有DateTime类型的创建日期。 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 我以字符串类型输入EnteredDate ,如下所示 2012年5 月16日

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". 在第二行中,我遇到了错误,因为String被识别为“ mm / dd / yy” 的有效DateTime I also tried DateTime.Parse(), Convert.ToDateTime() and got same error. 我还尝试了DateTime.Parse(),Convert.ToDateTime()并得到了相同的错误。 How can I filter this product list by create date? 如何按创建日期过滤此产品列表?

"mm" is minutes, and your year is 4 digits, not 2. You want "MM/dd/yyyy", if your format is really always that. “MM”是分钟,你的年是4个位数,而不是2.你想要的“MM / DD / YYYY”,如果你的格式是真的总是。 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);

呼叫

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM