比较类型字符串的日期 [英] Compare date of type string

查看:133
本文介绍了比较类型字符串的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了带有名称发票的模型类,一列是该日期。

公共类发票

{

公共字符串日期{get; set;}

}



控制器代码是:



列表< invoice> lst = db.Invoices.Where(u => u.Date.CompareTo(to)< = 0&& u.Date.CompareTo(frm)> = 0).ToList();
当我想要两个月之间的数据时,


。 lst还显示了另一个月的所有数据。

还建议我如何比较数据类型字符串的两个日期?

i have create model class with name invoice, and one column is that date.
public class Invoice
{
public string date{get;set;}
}

controller code is:

List<invoice> lst = db.Invoices.Where(u => u.Date.CompareTo(to) <= 0 && u.Date.CompareTo(frm)>=0).ToList();

when i want data between two month. lst showing all the data from another month also.
also suggest me how to compare two date of datatype string?

推荐答案

简单:don 't。



永远不要尝试将日期作为字符串进行比较 - 有很多方法可以出错。

始终转换在用户输入之后,尽快将字符串日期从字符串更改为DateTime,并在将它们呈现给用户之前尽可能晚地将它们转换回字符串。如果你不这样做,那么一切都会出错。例如,如果您有两个用户以不同的格式输入日期,除非您知道每个使用的格式(并且您只能在输入完成时获得该格式),否则您无法安全地比较它们:

01/02/03可能是2003年2月1日,2003年1月2日,或2001年2月3日,具体取决于您的用户的国籍。另一个用户可以输入02/01/03完全相同的日期...如果您将日期存储和操作为字符串,则不知道它是什么!
Simple: don't.

Never try to compare dates as strings - there are far, far too many ways it can go wrong.
Always convert dates from string to DateTime as soon as possible after the user input them, and convert them back to strings as late as possible before you present them back to the user. If you don't there are just too many ways that everything can go wrong. For example, if you have two users entering dates in different formats, unless you know what format each used (and you can only get that when the input is done) you can't safely compare them at all:
01/02/03 could be 1st Feb 2003, 2nd Jan 2003, or 3rd Feb 2001 depending on the nationality of your user. A different user could enter 02/01/03 for exactly the same date...and if you store and manipulate your dates as strings you don't know which it is!


这篇关于比较类型字符串的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆