这篇文章主要介绍了c#日期间隔计算类,最后有使用方法,需要的朋友可以参考下
///
/// 计算日期的间隔(静态类)
///
public static class dateTimeDiff
{
#region 计算日期间隔
///
/// 计算日期间隔
///
/// 要参与计算的其中一个日期字符串
/// 要参与计算的另一个日期字符串
///
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("字符串参数不正确!");
}
}
#endregion
#region 计算日期间隔
///
/// 计算日期间隔
///
/// 要参与计算的其中一个日期
/// 要参与计算的另一个日期
///
public static TimeSpan toResult(DateTime d1, DateTime d2)
{
TimeSpan ts;
if (d1 > d2)
{
ts = d1 - d2;
}
else
{
ts = d2 - d1;
}
return ts;
}
#endregion
#region 计算日期间隔
///
/// 计算日期间隔
///
/// 要参与计算的其中一个日期字符串
/// 要参与计算的另一个日期字符串
/// 决定返回值形式的枚举
///
public static int[] toResult(string d1, string d2, diffResultFormat drf)
{
try
{
DateTime date1 = DateTime.Parse(d1);
DateTime date2 = DateTime.Parse(d2);
return toResult(date1, date2, drf);
}
catch
{
throw new Exception("字符串参数不正确!");
}
}
#endregion
#region 计算日期间隔
///
/// 计算日期间隔
///
/// 要参与计算的其中一个日期
/// 要参与计算的另一个日期
/// 决定返回值形式的枚举
///
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
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
}
#endregion
}
#region 关于返回值形式的枚举
///
/// 关于返回值形式的枚举
///
public enum diffResultFormat
{
///
/// 年数和月数
///
yymm,
///
/// 年数
///
yy,
///
/// 月数
///
mm,
///
/// 天数
///
dd,
}
#endregion
以上就是c#日期间隔计算示例的详细内容,更多请关注0133技术站其它相关文章!