How to create a list of days starting with today and going back the last 30 days in C#

1 Answer

0 votes
using System;
using System.Collections.Generic;

class Last30Days
{
    // Method to get the last 30 days' day-of-month values
    public static List<int> GetLast30Days() {
        List<int> days = new List<int>();

        // Get today's date
        DateTime today = DateTime.Now;

        // Loop through the last 30 days
        for (int i = 0; i < 30; i++) {
            // Subtract 'i' days to get past date
            DateTime pastDate = today.AddDays(-i); // Subtract 'i' days
            days.Add(pastDate.Day); // Add the day of the month to the list
        }

        return days;
    }

    static void Main(string[] args)
    {
        // Get the last 30 days
        List<int> days = GetLast30Days();

        Console.Write("Days: [");
        for (int i = 0; i < days.Count; i++) {
            Console.Write(days[i]);
            if (i < days.Count - 1) {
                Console.Write(", ");
            }
        }
        Console.WriteLine("]");
    }
}


/*
run:

Days: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12]

*/

 



answered Apr 10, 2025 by avibootz
...