Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/date/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# C语言中的日期计算#_C#_Date - Fatal编程技术网

C# C语言中的日期计算#

C# C语言中的日期计算#,c#,date,C#,Date,我将日期作为字符串,格式如下: yyyy-mm-dd e、 g 我想检查两个日期,看看date1是否比date2小 伪代码: string date1 = "2011-08-29"; string date2 = "2011-09-29"; if (date1 < date2) { MessageBox.Show("First date is smaller!"); } string date1=“2011-08-29”; 字符串date2=“2011-09-29”; 如果(

我将日期作为字符串,格式如下:

yyyy-mm-dd
e、 g

我想检查两个日期,看看date1是否比date2小

伪代码:

string date1 = "2011-08-29";
string date2 = "2011-09-29";

if (date1 < date2) {
    MessageBox.Show("First date is smaller!");
}
string date1=“2011-08-29”;
字符串date2=“2011-09-29”;
如果(日期1<日期2){
Show(“第一个日期更小!”);
}

将两个字符串都转换为DateTime变量,并使用
DateTime.CompareTo
在此处找到

使用
Convert.ToDateTime(date1)
进行转换

解决方案可能看起来像

If (Convert.ToDateTime(date1).CompareTo(Convert.ToDateTime(date2)) < 0){
MessageBox.Show("First date is smaller!");
}
If(Convert.ToDateTime(date1).CompareTo(Convert.ToDateTime(date2))<0{
Show(“第一个日期更小!”);
}

您可以通过解析该字符串创建一个
DateTime
对象,然后继续使用该逻辑。 例:

为了安全解析,使用
DateTime.TryParse(date1,out dateTime1)

DateTime date1=new DateTime(2009,8,1,0,0);
DateTime date2=新的日期时间(2009,8,1,12,0,0);
int result=DateTime.Compare(date1,date2);
字符串关系;
如果(结果<0)
relationship=“早于”;
否则如果(结果==0)
relationship=“与同时”;
其他的
relationship=“晚于”;

如果保证日期始终采用精确格式,则字符串比较就足够了。

如果日期采用
YYYY-mm-dd
格式,则无需解析。你的例子做得很好。

那么,你的问题是什么?
yyyy-mm-dd
格式确实允许使用原始字符串正确比较日期…您可以使用
date1。CompareTo(date2)<0
如果您真的想在字符串上进行比较事实上,将yyy-mm-dd作为ISO 8601推荐的日期格式的一个基本原理是,它有一个字典顺序,可以很容易地排序。@PeeHaa,我明白了。事实上,在C#中没有为字符串定义关系运算符(但它们在VB.NET IIRC中)。@PeeHaa那么你是在问如何比较C#中的字符串吗?使用String.Compare方法。它不是。请看我在问题下的评论。它将始终采用这种格式。这就是我选择这种格式的原因。但是,如果我尝试比较它们,就会得到一个错误。请参阅我在问题下的评论。请参阅丹尼尔·希尔加思对您的评论的评论。您需要使用CompareTo函数-
If (Convert.ToDateTime(date1).CompareTo(Convert.ToDateTime(date2)) < 0){
MessageBox.Show("First date is smaller!");
}
DateTime dateTime1 = DateTime.Parse(date1);
DateTime date1 = new DateTime(2009, 8, 1, 0, 0, 0);
DateTime date2 = new DateTime(2009, 8, 1, 12, 0, 0);
int result = DateTime.Compare(date1, date2);
string relationship;

if (result < 0)
   relationship = "is earlier than";
else if (result == 0)
   relationship = "is the same time as";         
else
   relationship = "is later than";