繁体   English   中英

C#中两个日期之间的差异

[英]Difference between two dates in C#

在一个senario中,我需要找出两个日期之间的差异,例如开始日期是2012年1月1日,结束日期是2013年10月10日。我需要将输出设为1.9年。

int tDays=(ToDate.Subtract(FromDAte).Days+1);
int years = tDays / 365;
int months = (tDays % 365) / 31;

但是,对于Le年,这种计算是错误的。

我的Noda Time库正是为这种事情而构建的:

LocalDate start = new LocalDate(...);
LocalDate end = new LocalDate(...);
Period period = Period.Between(start, end);
Console.WriteLine("{0} years, {1} months, {2} days",
                  period.Years, period.Months, period.Days);

请注意,这将涉及的事实,几个月并不总是相同的长度-因此,例如,到3月1日2013年2月1日(28天)== 1个月,而3月1日至3月29日(也28天)= = 0个月28天。

这将让你月,年和天-我不知道你在哪里得到“1.9”基于你的榜样,除非你使用“years.months”,这我会强烈反对 ,因为它看起来像你意思是“非常接近2年”。

您应该使用有关日期创建一个DateTime对象。 然后,您可以创建两个DateTimes之间的时差,结果是一个TimeSpan对象。

尝试这个!

        DateTime date_start = new DateTime(2011, 1, 30);
        DateTime date_end = new DateTime(2012, 2, 29);//leap year

        DateTime tmp_dtStart = date_start;
        DateTime tmp_dtEnd = date_end;

        //FIX FOR LEAP YEAR
        //If the day is the last day of the month just adding 1 day. This might solve the leap year problem.            
        if (tmp_dtStart.Day == DateTime.DaysInMonth(tmp_dtStart.Year, tmp_dtStart.Month))
        {
           tmp_dtStart= tmp_dtStart.AddDays(1);
        }
        if (tmp_dtEnd.Day == DateTime.DaysInMonth(tmp_dtEnd.Year, tmp_dtEnd.Month))
        {
           tmp_dtEnd= tmp_dtEnd.AddDays(1);
        }

        DateTime diff = new DateTime((tmp_dtEnd - tmp_dtStart).Ticks);

        int years = diff.Year - 1;
        int month = diff.Month - 1;

        string outStr = string.Format("{0}.{1} years", years, month);

我已经编辑了以前的代码来处理the年。

逻辑是,(我使用了2个临时日期变量,而未触及实际日期变量)检查日期是否等于该月的最后一天。 如果是,则将1添加到一天,然后移动到下个月。

我已经测试了一些工作正常的日期。

如果您只需要一个值,则可以使用Ticks属性。 例如:

//Calculate Ticks in one year
var now = DateTime.Now;
var ticksInYear = (now.AddYears(1) - now).Ticks;

//Create some dates
DateTime first = DateTime.Today.AddYears(-1);
DateTime second = Datetime.Today;

//Get the difference
long value = (second.Ticks - first.Ticks)/ticksInYear;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM