C# 通过一个开始时间和结束时间 按【AddDays】拆分成一个数组

时间:2021-12-21 17:05:11
       /// <summary>
        /// 返回按AddDays拆分的时间段(包含多个逗号隔开)
        /// </summary>
        public static string StrTimes(DateTime starttime, DateTime endtime, int AddDays)
        {
            DateTime nowtime = starttime; string strtimes = starttime.ToString("yyyy-MM-dd HH:mm:ss") + ",";
            do
            {
                nowtime = nowtime.AddDays(AddDays);
                if (nowtime < endtime)
                    strtimes += nowtime.ToString("yyyy-MM-dd HH:mm:ss") + ",";
                else
                    strtimes += endtime.ToString("yyyy-MM-dd HH:mm:ss") + ",";

            } while (nowtime < endtime);

            return strtimes.Trim(',');
        }
        /// <summary>
        /// 根据时间段和AddDays来拆分, 返回一个时间数组
        /// </summary>
        public static DateTime[] ArrayTime(DateTime starttime, DateTime endtime, int AddDays)
        {
            string strtime = StrTimes(starttime, endtime, AddDays);

            string[] arrstrtime = strtime.Split(new String[] { "," }, StringSplitOptions.RemoveEmptyEntries);

            DateTime[] arrayTimes = arrstrtime.ToList().ConvertAll((a) => { return DateTime.Parse(a); }).ToArray();
            return arrayTimes;
        }