C#比较两个没有年份的日期 [英] C# compare two dates without year

查看:134
本文介绍了C#比较两个没有年份的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想比较不包括年份的两个日期。



Ex。



输入:FromDate :3月1日,日期:3月5日



然后,这两个日期之间的所有记录都应该在是否有任何年份。没关系。



所以请任何人都可以帮我解决这个问题。



提前致谢。

解决方案

您可以人为地介绍您的比较年份。例如,

 string s1 =15/03; 
string s2 =01/03;
DateTime d1 = DateTime.Parse(s1 +/ 2014);
DateTime d2 = DateTime.Parse(s2 +/ 2014);
TimeSpan t = d1.Subtract(d2);





您需要确保s1始终是较晚的日期,您可能需要考虑重叠年底,例如12月20日至1月3日。但原则仍然有效 - 只需选择任意一年。



注意闰年


在c#中你可以将这两个日期的日期部分和月份分开,可以比较并保持年份。



日期时间d1 = somedate; 
日期时间d2 = someotherdate;

int day1 = d1.Day;
int day2 = d2.Day;

int Month1 = d1.Month;
int Month2 = d2.Month;
if (day1 == day2&& Month1 == Month2)
{
// 您的逻辑在这里
}
其他
{
// 日期不匹配......
}


I would like to compare two dates excluding years.

Ex.

Input: FromDate: 01 March, ToDate: 05 March

then all records between these two dates should be come whether there is any year. It does not matter.

So please anyone can help me in this issue.

Thanks in advance.

解决方案

You could artifically introduce the year for your comparison. E.g.

string s1 = "15/03";
string s2 = "01/03";
DateTime d1 = DateTime.Parse(s1 + "/2014");
DateTime d2 = DateTime.Parse(s2 + "/2014");
TimeSpan t = d1.Subtract(d2);



You would need to ensure that s1 is always the later "date" and you may want to consider the overlap over the end of the year e.g. 20 December to 03 January. But the principle would still work - just choose an arbitrary year.

Watch out for leap years too


in c# you can saperate the day part and month part of both the dates and can compare that and leave year as it is.

Datetime d1 = somedate;
Datetime d2 = someotherdate;

int day1 = d1.Day;
int day2 = d2.Day;

int Month1 = d1.Month;
int Month2 = d2.Month;
 if(day1 == day2 && Month1 == Month2)
{
//your logic goes here 
}
else 
{
//Date not matching...
}


这篇关于C#比较两个没有年份的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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