string time1="20160101";
string time2="20171231";
求这2个时间的间隔,结果为2年;
我是这么写的
DateTime d1 = DateTime.ParseExact(time2, "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture);
DateTime d2 = DateTime.ParseExact(time1, "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture);
int month = (d1.Year - d2.Year) * 12 + (d1.Month - d2.Month);
int year;
if (month % 12 == 0){year = month / 12;}
else{year = month / 12 + 1;}
请问还有什么好点的方法吗,谢谢
Subtract
double days = d1.Subtract(d2).TotalDays;
http://www.cnblogs.com/huangfr/archive/2012/04/06/2435099.html
DateTime dt1 = DateTime.Now;
DateTime dt2 = DateTime.Now.AddDays(-7);
TimeSpan ts = dt1 - dt2;
int days = ts.Days; //dt1和dt2相差多少天
TimeSpan才是王道