[英]Year, Month, Day differ counter(Date) in C#
我想知道是否已经有一个已实现的Datecounter可以计算出一个日期与另一个日期之间有多少年,月和日的差异? 如果存在差异,该函数将计算差异的年数,月数和天数并将其存储,我们只需要使用Console.Writeline(timecomparer.yearDiffCounter);
告诉他们相差多少年
例如(伪代码,并非100%正确)!
Date date1 = new Date("2013-07-05");
Date date2 = new Date("2010-07-05");
TimeComparer compare = new TimeComparer();
compare.differDate(date1,date2); //here it will count and give 3 years difference
使用Noda Time :
LocalDate date1 = new LocalDate(2013, 07, 05);
LocalDate date2 = new LocalDate(2010, 07, 05);
Period period = Period.Between(date2, date1, PeriodUnits.YearMonthDay);
Console.WriteLine("{0} years, {1} months, {2} days",
period.Years, period.Months, period.Days);
// "3 years, 0 months, 0 days"
强大的时间解决方案是Jon Skeet的Noda Time 。
public string DateDiff(DateTime DateTime1, DateTime DateTime2)
{
string dateDiff = null;
TimeSpan ts1 = new TimeSpan(DateTime1.Ticks);
TimeSpan ts2 = new TimeSpan(DateTime2.Ticks);
TimeSpan ts = ts1.Subtract(ts2).Duration();
dateDiff = ts.Days.ToString() + "day"
+ ts.Hours.ToString() + "hours"
+ ts.Minutes.ToString() + "minutest"
+ ts.Seconds.ToString() + "seconds";
return dateDiff;
}
我可以改变的方式
C#中对DateTime
对象的布尔运算会产生TimeSpan
对象
DateTime Yesterday = DateTime.Now().AddDays(-1);
DateTime Today = DateTime.Now();
TimeSpan difference = Today - Yesterday;
时间跨度可以告诉您它有多少天,几小时,几分钟,几秒钟等等。
如果您想从Timespan获得数年,请查看brianary的答案
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.