以前在一家大公司由于不能使用存储过程,直接用代码写了求当天,昨天,本周,上周,本月,上月的函数。给大家参考。
/// <summary>
/// 根据日期类型获取相应的时间段
/// 创建标识:yangys20080512
/// </summary>
/// <param name="dateType">日期类型</param>
/// <param name="strDateStart">开始日期(输出参数)</param>
/// <param name="strDateEnd">结束日期(输出参数)</param>
/// <returns>void</returns>
private void GetDateTime(int dateType, out string strDateStart, out string strDateEnd)
{
strDateStart = "";
strDateEnd = "";
DateTime dateNow=DateTime.Now;
DateTime dateTemp;
int i;
string strTemp;
switch (dateType)
{
case 1:
//当天
strDateStart = dateNow.ToShortDateString() + " 00:00";
strDateEnd = dateNow.ToShortDateString() + " 23:59";
break;
case 2:
//昨天
dateTemp=dateNow.AddDays(-1);
strDateStart = dateTemp.ToShortDateString() + " 00:00";
strDateEnd = dateTemp.ToShortDateString() + " 23:59";
break;
case 3:
//本周
i=0;
strTemp = dateNow.DayOfWeek.ToString();
//获取今天是星期几
switch (strTemp)
{
case "Monday":
i =0;
break;
case "Tuesday":
i = 1;
break;
case "Wednesday":
i = 2;
break;
case "Thursday":
i = 3;
break;
case "Friday":
i = 4;
break;
case "Saturday":
i = 5;
break;
case "Sunday":
i =6;
break;
}
strDateStart = dateNow.AddDays(-i).ToShortDateString() + " 00:00";
strDateEnd = dateNow.AddDays(6 - i).ToShortDateString() + " 23:59";
break;
case 4:
//上周
i = 0;
strTemp = dateNow.DayOfWeek.ToString();
//获取今天是星期几
switch (strTemp)
{
case "Monday":
i = 0;
break;
case "Tuesday":
i = 1;
break;
case "Wednesday":
i = 2;
break;
case "Thursday":
i = 3;
break;
case "Friday":
i = 4;
break;
case "Saturday":
i = 5;
break;
case "Sunday":
i = 6;
break;
}
i += 1;
dateTemp = dateNow.AddDays(-i);
strDateStart = dateTemp.AddDays(-6).ToShortDateString() + " 00:00";
strDateEnd = dateNow.AddDays(-i).ToShortDateString() + " 23:59";
break;
case 5:
//本月
strTemp = dateNow.ToString("yyyy-MM-dd");
strDateStart = strTemp.Substring(0, 8) + "01 00:00";
strTemp = dateNow.AddMonths(1).ToString("yyyy-MM-dd");
strTemp = strTemp.Substring(0, 8) + "01";
dateTemp = Convert.ToDateTime(strTemp);
strTemp = dateTemp.AddDays(-1).ToString("yyyy-MM-dd");
strDateEnd = strTemp + " 23:59";
break;
case 6:
//上月
dateNow = dateNow.AddMonths(-1);
strTemp = dateNow.ToString("yyyy-MM-dd");
strDateStart = strTemp.Substring(0, 8) + "01 00:00";
strTemp = dateNow.AddMonths(1).ToString("yyyy-MM-dd");
dateTemp = Convert.ToDateTime(strTemp.Substring(0, 8) + "01");
strTemp = dateTemp.AddDays(-1).ToString("yyyy-MM-dd");
strDateEnd = strTemp + " 23:59";
break;
}
}