如何解析字符串到DateTime?(How to parse string to DateTime?)

编程入门 行业动态 更新时间:2024-10-08 06:17:26
如何解析字符串到DateTime?(How to parse string to DateTime?)

我有产品列表,每个产品都有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);

更多推荐

本文发布于:2023-07-30 15:40:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1338803.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   DateTime   string   parse

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!