源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

c#日期间隔计算示例

  • 时间:2022-12-20 14:23 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:c#日期间隔计算示例
[u]复制代码[/u] 代码如下:
/// <summary> /// 计算日期的间隔(静态类) /// </summary> public static class dateTimeDiff { #region 计算日期间隔 /// <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("字符串参数不正确!"); } } #endregion #region 计算日期间隔 /// <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; } #endregion #region 计算日期间隔 /// <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, diffResultFormat drf) { try { DateTime date1 = DateTime.Parse(d1); DateTime date2 = DateTime.Parse(d2); return toResult(date1, date2, drf); } catch { throw new Exception("字符串参数不正确!"); } } #endregion #region 计算日期间隔 /// <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, 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 } #endregion } #region 关于返回值形式的枚举 /// <summary> /// 关于返回值形式的枚举 /// </summary> public enum diffResultFormat { /// <summary> /// 年数和月数 /// </summary> yymm, /// <summary> /// 年数 /// </summary> yy, /// <summary> /// 月数 /// </summary> mm, /// <summary> /// 天数 /// </summary> dd, } #endregion
[u]复制代码[/u] 代码如下:
DateTime sDate = Convert.ToDateTime("2014-1-16"); DateTime eDate = Convert.ToDateTime("2014-2-16"); int month = dateTimeDiff.toResult(sDate, eDate, diffResultFormat.mm)[0];
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部