// 将日期字符串解析为起止范围日期 // throw: // Exception public static void ParseDateRange(string strText, out string strStartDate, out string strEndDate) { strStartDate = ""; strEndDate = ""; int nRet = strText.IndexOf("-"); if (nRet == -1) { // 没有'-' if (strText.Length == 4) { strStartDate = strText + "0101"; strEndDate = strText + "1231"; return; } if (strText.Length == 6) { strStartDate = strText + "01"; DateTime start = DateTimeUtil.Long8ToDateTime(strStartDate); DateTime end = start.AddMonths(1); end = new DateTime(end.Year, end.Month, 1); // 下月1号 end = end.AddDays(-1); // 上月最后一号 strEndDate = strText + end.Day; return; } if (strText.Length == 8) { // 单日 strStartDate = strText; strEndDate = ""; return; } // text-level: 用户提示 throw new Exception( string.Format("日期字符串 '{0}' 格式不正确。应当为4/6/8字符", strText) ); } else { string strLeft = ""; string strRight = ""; strLeft = strText.Substring(0, nRet).Trim(); strRight = strText.Substring(nRet + 1).Trim(); if (strLeft.Length != strRight.Length) { // text-level: 用户提示 throw new Exception( string.Format("日期字符串 '{0}' 格式不正确。横杠左边的部分 '{1}' 和右边的部分 '{2}' 字符数应相等。", strText, strLeft, strRight) ); } if (strLeft.Length == 4) { strStartDate = strLeft + "0101"; strEndDate = strRight + "1231"; return; } if (strLeft.Length == 6) { strStartDate = strLeft + "01"; DateTime start = DateTimeUtil.Long8ToDateTime(strRight + "01"); DateTime end = start.AddMonths(1); end = new DateTime(end.Year, end.Month, 1); // 下月1号 end = end.AddDays(-1); // 上月最后一号 strEndDate = strRight + end.Day; return; } if (strLeft.Length == 8) { // 单日 strStartDate = strLeft; strEndDate = strRight; return; } // text-level: 用户提示 throw new Exception( string.Format("日期字符串 '{0}' 格式不正确。横杠左边或者右边的部分,应当为4/6/8字符", strText) ); } }