简体   繁体   中英

Get date of last seven days

I want to get date of last seven days from now.For example current date is

02-10-2016, get date of seven days like this

01-10-2016,30-09-2016,29-09-2016,28-09-2016,27-09-2016,26-09-2016

My code

string dt = DateTime.Now.ToString("yyyy-MM-dd");
DateTime lastWeek = dt.AddDays(-7.0);

AddDays is a part of DateTime , not of string .
You need to build your dates iteratively and then convert it to a 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

Try using 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

Test

  // 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"))));

Without LINQ, with a simple loop:

DateTime dt = DateTime.Now;

for (int i=0;i<7;i++)
{
      dt = dt.AddDays(-1);
      Console.WriteLine(dt.Date.ToShortDateString());
}

You are almost there, the AddDays method will add only a specific number of days to the given data and dives you the resulted date. But here in your case you need a list of dates, so you have to loop through those dates and get them as well. I hope the following method will help you to do this:

 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());
 }

Note : If you want to exclude the current date means you have to take the range from 7 and the count should be 7 . You can read more about Enumerable.Range here

If you call this method like the following means you will get the output as 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;
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM