#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
新聞熱點
疑難解答