Home > Back-end >  Random date generator
Random date generator

Time:12-02

Hey im looking for a random date generator that uses the date of the system how can i do it? i give an example, if the month is february i want 5 numbers between 1-28 and if the month is january i want 5 numbers between 1-31

ive tried to do it with

private Random gen = new Random();
DateTime RandomDay()
{
    DateTime start = new DateTime(1995, 1, 1);
    int range = (DateTime.Today - start).Days;           
    return start.AddDays(gen.Next(range));
}

but i didnt figured it out

CodePudding user response:

From my understanding you need to generate 5 random dates in a given month and year. Here is a method to do that:

List<DateTime> GetRandomDatesForYearAndMonth(int year, int month, int numberOfDates, Random randomizer)
{
    var result = new List<DateTime>();
    // Get number of days in month
    int days = DateTime.DaysInMonth(year, month);
    // Determine the candidate days
    var candidates = Enumerable.Range(1, days);
    for (int i=0;i<numberOfDates;i  )
    {
        // Pick a random element
        var dayIndex = randomizer.Next(candidates.Count());
        var day = candidates.ElementAt(dayIndex);
        // Add the date
        result.Add(new DateTime(year, month, day));
        // Remove it from the candidates
        candidates = candidates.Where(x => x != day);
    }
    return result;
}

You call it like this:

Random randomizer = new Random();
var result = GetRandomDatesForYearAndMonth(1995, 2, 5, randomizer);

I leave it to you to call it in a suitable loop and sanitize the arguments.

CodePudding user response:

Assuming you want a number of days in a random month between 1995 and now, you could use this method:

Random gen = new Random();

// returns a *list* of dates
public List<DateTime> GetRandomDatesInOneMonth(int count)
{
    // prepare the return value
    var result = new List<DateTime>();

    // count the total available days
    DateTime start = new DateTime(1995, 1, 1);
    int range = (int)(DateTime.Today - start).TotalDays;

    // get a random date in that range, to get the target month
    var target = start.AddDays(gen.Next(range));
    
    // get the number of days in this month, handling leap years
    var daysinmonth = DateTime.DaysInMonth(target.Year, target.Month);

    // repeat for the required amount of days
    for (int i=0; i<count; i  )
    {
        // get a day-number between 1 and daysinmonth, inclusive
        var day = gen.Next(daysinmonth)   1;

        // calculate the new date, and add to result
        result.Add(new DateTime(target.Year, target.Month, day));   
    }

    // finally, return the list
    return result;
}

And you can use it as

List<DateTime> fivedates = GetRandomDatesInOneMonth(5);

Do note that this list is unsorted and may contain duplicate dates. And it may get to the current month and select dates from there that are still to come.

  • Related