这是我之前写的一个共能的需求
前后天都可以这么写,前台写在js函数中。
日期:往期推7天
public string[] Day(string date)
{
string[] dateTimes = new string[7];// 日期节点
date = date.Replace('/', '-');
int pYears = Convert.ToInt32(date.Split('-')[0]);
int pMonths = Convert.ToInt32(date.Split('-')[1]);
int days = DateTime.DaysInMonth(pYears, pMonths);
int pDay = Convert.ToDateTime(date).Day;
string time1 = "";
string time2 = "";
for (int i = 0; i < 7; i++)
{
if(i!=0)
{
pDay = pDay - 1;
}
if (pMonths < 10)
{
time1 = "0" + pMonths;
}
else
{
time1 = Convert.ToString(pMonths);
}
if (pDay < 10)
{
time2 = "0" + pDay;
}
else
{
time2 =Convert.ToString(pDay);
}
string datetime1 = (pYears + "-" + time1 + "-" + time2);// 每天的开始时间也可以加上“00:00: 00”
int vMaxs = DateTime.DaysInMonth(pYears, pMonths);// 每个月的天数
string datetime2 = (pYears + "-" + time1 + "-" + time2);// 每天的结束时间“23 :59 :59”
// datetime1和datetime2两个选其中一个就OK了
for (int j = i; j <= i; j++)
{
dateTimes[i] = datetime1;
}
}
//数组 取反 因为我们是从最近的日期开始往前推,所以我们要把渠道的日期反过来从小到大,看需求,可写可不写
Array.Reverse(dateTimes);
return dateTimes;
}
日期:往前推5个月
public string[] datetomaxday(string date)
{
// 定义下标为6的原因是因为,我们要求的是往前推五个月是五个时间区间不是五个时间节点
string[] dateTimes = new string[6];// 8.30 9.30 10.30 11.30 12.30 01.30 六个时间节点
date = date.Replace('/', '-');//把 / 替换为 -
int pYears = Convert.ToInt32(date.Split('-')[0]);
int pMonths = Convert.ToInt32(date.Split('-')[1]);
int it = pYears + 1;
for (int i = 0; i < 6; i++)
{
if (pMonths == 1 && i == 1)
{
pYears = pYears - 1;
pMonths = 12;
}
else
{
if (pMonths == 1)
{
pMonths = pMonths - 0;
}
else
{
pMonths = pMonths - 1;
}
}
string datetime1 = (pYears + "-" + pMonths + "-01 00:00:00");// 求每个月月初的时间
int vMaxs = DateTime.DaysInMonth(pYears, pMonths);// 求所每个月的天数
string datetime2 = (pYears + "-" + pMonths + "-" + vMaxs + " 23:59:59");// 每个月月末的时间
// datetime1和datetime2两个选其中一个就OK了
for (int j = i; j <= i; j++)
{
dateTimes[i] = datetime2;
}
}
//数组 取反 因为我们是从最近的日期开始往前推,所以我们要把渠道的日期反过来从小到大,看需求,可写可不写
Array.Reverse(dateTimes);
return dateTimes;
}