How to create an array of days starting with today and going back the last 30 days in C

1 Answer

0 votes
#include <stdio.h>
#include <time.h>

void getLast30Days(int days[], int numDays) {
    time_t now = time(NULL); // Get current time

    for (int i = 0; i < numDays; ++i) {
        // Calculate the time 'i' days ago
        time_t past_time = now - (i * 24 * 60 * 60); // Subtract 'i' days in seconds

        // Convert to tm struct to extract the day
        struct tm *past_tm = localtime(&past_time);

        // Store the day of the month in the array
        days[i] = past_tm->tm_mday;
    }
}

int main() {
    int numDays = 30;                  // Number of days to process
    int days[30];                      // Array to store the last 30 days

    // Call the function to fill the array
    getLast30Days(days, numDays);

    printf("Days: [");
    for (int i = 0; i < numDays; ++i) {
        printf("%d", days[i]);
        if (i < numDays - 1) {
            printf(", ");
        }
    }
    printf("]\n");

    return 0;
}



/*
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
...