我有两个约会.一个日期是输入,另一个是DateTime.Now.我有它们的mm/dd/yyyy格式,它甚至可以是m/d/yy格式.两个日期都可DateTime?以为空,即数据类型是,因为我也可以将null作为输入传递.现在我想只用mm/dd/yyyy或m/d/yy格式比较两个日期.
Dam*_*ver 81
如果你有你的日期在日期时间变量,他们不具备的格式.
您可以使用该Date属性返回DateTime值,并将时间部分设置为午夜.所以,如果你有:
DateTime dt1 = DateTime.Parse("07/12/2011");
DateTime dt2 = DateTime.Now;
if(dt1.Date > dt2.Date)
{
//It's a later date
}
else
{
//It's an earlier or equal date
}
Run Code Online (Sandbox Code Playgroud)
FIr*_*nda 31
如果您在DateTime变量中有日期,那么它是一个DateTime对象,并且不包含任何格式.格式化日期表示为string调用DateTime.ToString方法并在其中提供格式时.
假设你有两个DateTime变量,你可以使用compare方法进行比较,
DateTime date1 = new DateTime(2009, 8, 1, 0, 0, 0);
DateTime date2 = new DateTime(2009, 8, 2, 0, 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";
Run Code Online (Sandbox Code Playgroud)
代码片段取自msdn.
首先,要了解DateTime对象没有格式化.它们只将年,月,日,小时,分钟,秒等存储为数值,并且当您想要以某种方式将其表示为字符串时,格式化会发生.您可以比较DateTime对象而不格式化它们.
要比较输入日期DateTime.Now,您需要先将输入解析为日期,然后再比较年/月/日部分:
DateTime inputDate;
if(!DateTime.TryParse(inputString, out inputDate))
throw new ArgumentException("Input string not in the correct format.");
if(inputDate.Date == DateTime.Now.Date) {
// Same date!
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
154676 次 |
| 最近记录: |