Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get date of last seven days

Tags:

c#

.net

datetime

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);
like image 627
user7063016 Avatar asked Nov 28 '22 13:11

user7063016


2 Answers

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
like image 69
Yeldar Kurmangaliyev Avatar answered Dec 11 '22 19:12

Yeldar Kurmangaliyev


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());
}
like image 37
5 revs, 4 users 77%SuperG Avatar answered Dec 11 '22 20:12

5 revs, 4 users 77%SuperG