C#使用DateTime获取某段日期范围内的所有日期与判断某个日期是否在某段日期范围内

时间:2021-12-25 17:19:27

C#中datetime的两个实用方法,分别是获取某段日期范围内的所有日期与判断某个日期是否在某段日期范围内。

    #region 获取某段日期范围内的所有日期
    /// <summary> 
    /// 获取某段日期范围内的所有日期,以数组形式返回  
    /// </summary>  
    /// <param name="dt1">开始日期</param>  
    /// <param name="dt2">结束日期</param>  
    /// <returns></returns>  
    private DateTime[] GetAllDays(DateTime dt1, DateTime dt2)
    {
        List<DateTime> listDays = new List<DateTime>();
        DateTime dtDay = new DateTime();
        for (dtDay = dt1; dtDay.CompareTo(dt2) <= 0; dtDay = dtDay.AddDays(1))
        {
            listDays.Add(dtDay);
        }
        return listDays.ToArray();
    }
    #endregion

    #region 判断某个日期是否在某段日期范围内
    /// <summary> 
    /// 判断某个日期是否在某段日期范围内,返回布尔值
    /// </summary> 
    /// <param name="dt">要判断的日期</param> 
    /// <param name="dt1">开始日期</param> 
    /// <param name="dt2">结束日期</param> 
    /// <returns></returns>  
    private bool IsInDate(DateTime dt, DateTime dt1, DateTime dt2)
    {
        return dt.CompareTo(dt1) >= 0 && dt.CompareTo(dt2) <= 0;
    }
    #endregion

   #region 获取某段日期范围内的所有日期
    /// <summary>
    /// 获取某段日期范围内的所有日期,以字符串形式返回 
    /// </summary>
    /// <param name="startDate">开始日期</param>
    /// <param name="endDate">结束日期</param>
    /// <returns></returns>
    protected string GetDate(DateTime startDate, DateTime endDate)
    {
        string result = string.Empty;
        for (DateTime temp = startDate.ToShortDateString(); temp <= endDate.ToShortDateString(); temp = temp.AddDays(1))
        {
            if (result == string.Empty)
            {
                result = temp.ToString();
            }
            else
            {
                result += "," + temp.ToString();
            }
        }
        return result;
    }
    #endregion