|
|
|
|
|
-
public static int[] toResult(DateTime d1, DateTime d2, diffResultFormat drf) { #region 数据初始化 DateTime max; DateTime min; int year; int month; int tempYear, tempMonth; if (d1 > d2) { max = d1; min = d2; } else { max = d2; min = d1; } tempYear = max.Year; tempMonth = max.Month; if (max.Month < min.Month) { tempYear--; tempMonth = tempMonth + 12; } year = tempYear - min.Year; month = tempMonth - min.Month; #endregion #region 按条件计算 if (drf == diffResultFormat.dd) { TimeSpan ts = max - min; return new int[] { ts.Days }; } if (drf == diffResultFormat.mm) { return new int[] { month + year * 12 }; } if (drf == diffResultFormat.yy) { return new int[] { year }; } return new int[] { year, month }; #endregion } } public enum diffResultFormat { yymm, yy, mm, dd, } 下面我们将使用这个类来计算日期间隔: string str1 = "2007-12-31"; string str2 = "2009-6-1"; int[] kk = dateTimeDiff.toResult(str1, str2, diffResultFormat.mm); Console.WriteLine(string.Format("间隔:{0}个月", kk[0])); DateTime date1 = DateTime.Parse(str1); DateTime date2 = DateTime.Parse(str2); int[] kk2 = dateTimeDiff.toResult(date1, date2, diffResultFormat.yymm); Console.WriteLine(string.Format("间隔:{0}年{1}个月", kk2[0], kk2[1])); 也可以用这个类来计算时间间隔: string str3 = "2009-5-31 1:55:24"; string str4 = "2009-6-1"; int kk3 =dateTimeDiff.toResult(str3, str4).Hours; Console.WriteLine(string.Format("间隔:{0}个小时", kk3));
发表于
2012-04-05 12:53
风云1号
阅读( 242)
评论()
收藏
举报
|
|