1. 程式人生 > >C#已知兩天日期求之間每一天日期字串集合

C#已知兩天日期求之間每一天日期字串集合

問題描述:

        在《C#判斷判斷某一時刻屬於什麼時間段》中提到的訂單處理系統中,有這麼一個需求,就是根據使用者選擇的兩個日期,去mdb中查詢在這連個日期之間的每一天的相關資訊,故需要用每一天的日期字串來拼接sql語句。

解決方法:

string dtpTime1="2018-01-01";
string dtpTime1="2018-10-01";
string[] sTimeArray = getTimeArray();
public static string[] getTimeArray(string time1, string time2)
{
	string[] strArray = new string[365];
	DateTime oldDate = new DateTime();
	DateTime newDate = new DateTime();
	try
	{
		oldDate = Convert.ToDateTime(time1);
		newDate = Convert.ToDateTime(time2);
	}
	catch
	{
	}

	TimeSpan ts = newDate - oldDate;
	int differenceInDays = ts.Days;
	DateTime tempTime = oldDate;
	string tempStr = "";
	for (int i = 0; i <= differenceInDays; i++)
	{
		if (i < strArray.Length)
		{
			tempStr = tempTime.ToString("yyyy-MM-dd");
			strArray[i] = tempStr;
			tempTime = tempTime.AddDays(1);
		}
	}

	return strArray;
}