How to create a list of random dates in C

1 Answer

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

// Generate a random date between two years using time_t
struct tm random_date(int startYear, int endYear) {
    // Convert start and end years to timestamps
    struct tm start = {0};
    start.tm_year = startYear - 1900;
    start.tm_mon = 0;
    start.tm_mday = 1;

    struct tm end = {0};
    end.tm_year = endYear - 1900;
    end.tm_mon = 11;
    end.tm_mday = 31;

    time_t start_t = mktime(&start);
    time_t end_t   = mktime(&end);

    // Uniform distribution over the timestamp range
    long long range = (long long)end_t - (long long)start_t;
    long long offset = rand() % range;

    time_t random_t = start_t + offset;

    // Convert back to tm
    struct tm result = *localtime(&random_t);

    return result;
}

int main() {
    srand((unsigned)time(NULL)); // Seed RNG

    int count = 10;
    struct tm *dates = malloc(sizeof(struct tm) * count);

    for (int i = 0; i < count; i++) {
        dates[i] = random_date(1990, 2030);
    }

    for (int i = 0; i < count; i++) {
        struct tm d = dates[i];
        printf("%d-%d-%d\n",
               d.tm_year + 1900,
               d.tm_mon + 1,
               d.tm_mday);
    }

    free(dates);
    
    return 0;
}



/*
run:

2000-9-6
2016-5-8
1997-11-22
2002-3-1
2028-12-21
2018-12-9
1998-2-15
1993-8-10
2007-12-16
2007-7-24

*/

 



answered 3 hours ago by avibootz
...