本文介绍了使用DateTime.Now减去日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我有一个下拉列表框,包含'过去7天','过去15天'和'过去30天'。



从此我需要在DateTime.Now和DateTime之间获取日期。现在 - 7天



请帮忙我怎么做到这一点。



提前致谢

Hi,

I have a Drop down List box, contains 'Last 7 days', 'Last 15 days' and 'Last 30 days'.

From this I need to get dates between DateTime.Now and DateTime.Now - 7 days

Please help me how to achieve this.

Thanks in advance

推荐答案

DataTable dt_dates = new DataTable();
dt_dates.Columns.Add("Date");

for (int i = 0; i < 7; i++)
{
    DataRow dr_dates = dt_dates.NewRow();
    dr_dates["Date"] = DateTime.Now.AddDays(-i).ToShortDateString();
    dt_dates.Rows.Add(dr_dates);
}

Combobox.Datasource = dt_dates;
Combobox.databind();


DateTime StartingDate= DateTime.Now.AddDays(-30);





然后使用以下方法获取这些日期之间的日期列表



private List< datetime> GetDateRange(DateTime StartingDate,DateTime EndingDate)

{

if(StartingDate> EndingDate)

{

return null;

}

List< datetime> rv = new List< datetime>();

DateTime tmpDate = StartingDate;

do

{

rv .Add(tmpDate);

tmpDate = tmpDate.AddDays(1);

} while(tmpDate< = EndingDate);

返回rv;

}



then get list of dates between these dates using below method

private List<datetime> GetDateRange(DateTime StartingDate, DateTime EndingDate)
{
if (StartingDate > EndingDate)
{
return null;
}
List<datetime> rv = new List<datetime>();
DateTime tmpDate = StartingDate;
do
{
rv.Add(tmpDate);
tmpDate = tmpDate.AddDays(1);
} while (tmpDate <= EndingDate);
return rv;
}


int count = 7;
var dates = Enumerable.Range(1-count, count).Select(i => DateTime.Today.AddDays(i));


这篇关于使用DateTime.Now减去日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 02:14