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

1 Answer

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

#define DAYS 30

// Function to get the last `numDays` dates in YYYY-MM-DD format
void getLastNDates(int numDays, char dates[][11]) {
    time_t now = time(NULL);
    struct tm date;
    char date_str[11]; // Format: YYYY-MM-DD // // 2025-04-10 // 10 chars + null

    for (int i = 0; i < numDays; i++) {
        date = *localtime(&now);
        strftime(date_str, sizeof(date_str), "%Y-%m-%d", &date); // Format date
        snprintf(dates[i], sizeof(date_str), "%s", date_str);    // Copy to array
        now -= 86400; // Subtract one day (86400 seconds)
    }
}

int main() {
    char dates[DAYS][11]; // Array to store the last 30 dates

    // Call the function to populate the dates array
    getLastNDates(DAYS, dates);

    for (int i = 0; i < DAYS; i++) {
        printf("%s\n", dates[i]);
    }

    return 0;
}



/*
run:

2025-04-10
2025-04-09
2025-04-08
2025-04-07
2025-04-06
2025-04-05
2025-04-04
2025-04-03
2025-04-02
2025-04-01
2025-03-31
2025-03-30
2025-03-29
2025-03-28
2025-03-27
2025-03-26
2025-03-25
2025-03-24
2025-03-23
2025-03-22
2025-03-21
2025-03-20
2025-03-19
2025-03-18
2025-03-17
2025-03-16
2025-03-15
2025-03-14
2025-03-13
2025-03-12

*/

 



answered Apr 10 by avibootz
...