public static class dateTimeDiff
{
/// <summary>
/// 计算日期间隔
/// </summary>
/// <param name="d1">要参与计算的其中一个日期字符串</param>
/// <param name="d2">要参与计算的另一个日期字符串</param>
/// <returns>一个表示日期间隔的TimeSpan类型</returns>
public static TimeSpan toResult(string d1, string d2)
{
try
{
DateTime date1 = DateTime.Parse(d1);
DateTime date2 = DateTime.Parse(d2);
return toResult(date1, date2);
}
catch
{
throw new Exception("字符串参数不正确!");
}
}
/// <summary>
/// 计算日期间隔
/// </summary>
/// <param name="d1">要参与计算的其中一个日期</param>
/// <param name="d2">要参与计算的另一个日期</param>
/// <returns>一个表示日期间隔的TimeSpan类型</returns>
public static TimeSpan toResult(DateTime d1, DateTime d2)
{
TimeSpan ts;
if (d1 > d2)
{
ts = d1 - d2;
}
else
{
ts = d2 - d1;
}
return ts;
}
/// <summary>
/// 计算日期间隔
/// </summary>
/// <param name="d1">要参与计算的其中一个日期字符串</param>
/// <param name="d2">要参与计算的另一个日期字符串</param>
/// <param name="drf">决定返回值形式的枚举</param>
/// <returns>一个代表年月日的int数组,具体数组长度与枚举参数drf有关</returns>
public static int[] toResult(string d1, string d2, diffFormat drf)
{
try
{
DateTime date1 = DateTime.Parse(d1);
DateTime date2 = DateTime.Parse(d2);
return toResult(date1, date2, drf);
}
catch
{
throw new Exception("字符串参数不正确!");
}
}
/// <summary>
/// 计算日期间隔
/// </summary>
/// <param name="d1">要参与计算的其中一个日期</param>
/// <param name="d2">要参与计算的另一个日期</param>
/// <param name="drf">决定返回值形式的枚举</param>
/// <returns>一个代表年月日的int数组,具体数组长度与枚举参数drf有关</returns>
public static int[] toResult(DateTime d1, DateTime d2, diffFormat 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 == diffFormat.Day)
{
TimeSpan ts = max - min;
return new int[] { ts.Days };
}
if (drf == diffFormat.Month)
{
return new int[] { month + year * 12 };
}
if (drf == diffFormat.Year)
{
return new int[] { year };
}
return new int[] { year, month };
#endregion
}
}
/// <summary>
/// 关于返回值形式的枚举
/// </summary>
public enum diffFormat
{
/// <summary>
/// 年数和月数
/// </summary>
YearMonth,
/// <summary>
/// 年数
/// </summary>
Year,
/// <summary>
/// 月数
/// </summary>
Month,
/// <summary>
/// 天数
/// </summary>
Day,
}
例:
DateTime dt1 = DateTime.Parse(dt.Rows[0]["mtime"].ToString());
DateTime dt2 = DateTime.Parse(dt.Rows[count - 1]["mtime"].ToString());
int[] kk = dateTimeDiff.toResult(dt1, dt2, diffFormat.Month);
本文转自94cool博客园博客,原文链接:http://www.cnblogs.com/94cool/archive/2011/06/13/2079795.html,如需转载请自行联系原作者