![](/img/trans.png)
[英]How Can I Write a LINQ Query to Get Content Within the Last Seven Days?
[英]Get date of last seven days
我想從現在開始過去七天的日期。例如,當前日期是
02-10-2016,
像這樣得到七天的日期
01-10-2016,30-09-2016,29-09-2016,28-09-2016,27-09-2016,26-09-2016
我的代碼
string dt = DateTime.Now.ToString("yyyy-MM-dd");
DateTime lastWeek = dt.AddDays(-7.0);
AddDays
是DateTime
的一部分,而不是string
。
您需要迭代地構建日期,然后將其轉換為字符串。
DateTime[] last7Days = Enumerable.Range(0, 7)
.Select(i => DateTime.Now.Date.AddDays(-i))
.ToArray();
foreach (var day in last7Days)
Console.WriteLine($"{day:yyyy-MM-dd}"); // Any manipulations with days go here
嘗試使用Linq :
var date = new DateTime(2016, 10, 2);
var result = Enumerable.Range(1, 7)
.Select(day => date.Date.AddDays(- day))
.ToArray(); // if you want to represent dates as an array
測試
// 01-10-2016,30-09-2016,29-09-2016,28-09-2016,27-09-2016,26-09-2016,25-09-2016
Console.Write(string.Join(",", result.Select(d => d.ToString("dd-MM-yyyy"))));
沒有LINQ,只需一個簡單的循環:
DateTime dt = DateTime.Now;
for (int i=0;i<7;i++)
{
dt = dt.AddDays(-1);
Console.WriteLine(dt.Date.ToShortDateString());
}
您幾乎就在那里,AddDays方法只會向給定數據添加特定天數,並將結果日期分給您。 但在這種情況下,你需要一個日期列表,所以你必須循環這些日期並獲得它們。 我希望以下方法可以幫助您做到這一點:
public static string GetLast7DateString()
{
DateTime currentDate = DateTime.Now;
return String.Join(",",Enumerable.Range(0, 7)
.Select(x => currentDate.AddDays(-x).ToString("dd-MM-yyyy"))
.ToList());
}
注意:如果要排除當前日期,則意味着必須從7
,計數應為7
。 您可以在此處閱讀有關Enumerable.Range
更多信息
如果您按以下方式調用此方法,您將得到輸出為24-10-2016,23-10-2016,22-10-2016,21-10-2016,20-10-2016,19-10-2016,18-10-2016
string opLast7Days = GetLast7DateString();
public static List<DateTime> getLastSevenDate(DateTime currentDate)
{
List<DateTime> lastSevenDate = new List<DateTime>();
for (int i = 1; i <= 7; i++)
{
lastSevenDate.Add(currentDate.AddDays(-i));
}
return lastSevenDate;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.