如何比较DateTime C#月份和周



我需要比较C中的日期#如果日期小于12个月,我需要设置一个布尔值

我的代码是

    String d  = "26/06/10";
    DateTime dt = DateTime.ParseExact(d, "dd/MM/yy", null);
    if ((dt > DateTime.Now.AddMonths(-12)  ) )
    {
        Console.WriteLine("It is less than 12 months");
    }
    else
    {
        Console.WriteLine("It is more than 12 months");
    }

是比较c#中日期的最佳方式。类似地,我需要比较日期是否少于两周

感谢的任何帮助

感谢

sup

您可以使用TimeSpan来获得两个DateTime值之间的差值

String d = "26/06/10";
DateTime dt = DateTime.ParseExact(d, "dd/MM/yy", null);
DateTime dt2 = DateTime.Now.AddMonths(-12);
TimeSpan ts = dt - dt2;

您可以使用ts.Days来比较

您可以进行

DateTime date2 = DateTime.Now.AddMonths(-12);
  //Or if you want to neglect the time part you could do
DateTime date2 = new DateTime(DateTime.Now.Year,DateTime.Now.Month,DateTime.Now.Day,0,0,0).AddMonths(-12);
String d = "26/06/10"; 
DateTime date1 = DateTime.ParseExact(d, "dd/MM/yy", null);
int result = DateTime.Compare(date1, date2);
string res;
if (result < 0)
   Console.WriteLine("It is less than 12 months"); 
else if (result == 0)
   res = "is the equal";         
else
    Console.WriteLine("It is more than 12 months"); 

代码片段的问题是,即使日期相等,它也会输出"它超过12个月"。

两周:

if (dt1.Subtract(dt2).Days > 14)
{
    ...
}  

对于12个月(一年)(考虑每月的哪一天并不重要):

var monthDifference = ((dt1.Year - dt2.Year) * 12) + dt1.Month - dt2.Month

为了更清楚地理解:您不想比较两个日期(或DateTimes),而是要比较两个时间跨度。即现在与您提供的日期之间的时间差,以及12个月的时间跨度。

String d = "26/06/10";
DateTime dt = DateTime.ParseExact(d, "dd/MM/yy", CultureInfo.InvariantCulture);
TimeSpan deltaTimeSpan = dt - DateTime.Now;      // get the time difference between now and the time given
TimeSpan twelveMonths = new TimeSpan(365,0,0,0); // get a time span of 12 months
// round the amount of days down and always supply a positive number of days
int deltaTime = Convert.ToInt32(Math.Abs(Math.Floor(deltaTimeSpan.TotalDays)));
if (twelveMonths.TotalDays > deltaTime)
{
    Console.WriteLine(string.Format("It is less than 12 months ({0} days).", deltaTime));
}
else if (twelveMonths.TotalDays < deltaTime)
{
    Console.WriteLine(string.Format("It is more than 12 months ({0} days).", deltaTime));
}
else
{
    Console.WriteLine(string.Format("The difference in time is exactly 12 months. ({0} days).", deltaTime);
}

请注意,这个例子当然没有考虑闰年。代码确实考虑了要与之比较的年份是过去还是未来(通过将TimeSpan转换为正值并与之进行比较)。

调整上述代码以在两周或任何其他时间段内执行相同操作应该足够简单。只需更改我命名为"twelveMonths"的TimeSpan。

DateTime date1 = DateTime.Now.AddMonths(-12)
if(DateTime.Compare(dt, date1 )
{
//provided date is within 12 months
}
else
{
//provided date is after 12 months
}

相关内容

  • 没有找到相关文章

最新更新