按年龄范围计算出生日期



例如 70,105 - 计算符合参数年龄范围的任何出生日期

    CalculateDob(int youngestAge, int oldestAge)
     {
        Random r = new Random();
        int age = 0;
        age = r.Next(70, 105);
        var year = DateTime.Now.Year - age;
        var month = r.Next(1, 12);
        var day = r.Next(1, 28);
        return new DateTime(year, month, day); 
    }

我目前的解决方案几乎可以工作,但在某些边缘情况下失败,即在某些情况下返回 69,因为我认为一个月的问题。

有什么建议吗?

你之所以有69岁,有时是因为如果CalculateDob返回的月份是当月之后的月份(DateTime.Now);那么Dob仍然不会达到70岁。此外,您应该从方法中取出随机构造函数,并使其静态,这样您就不会在每次调用期间都播种 rand 生成器。

public static void Main(string[] args)
{
    for (int i = 0; i < 100; i++)
    {
        var birthDate = CalculateDob(70, 105);
        var now = DateTime.Now;
        int age = now.Year - birthDate.Year;
        if (now.Month < birthDate.Month || (now.Month == birthDate.Month && now.Day < birthDate.Day))
        {
            age--;
        }
        Console.WriteLine(age);                
    }
}
//Construct this as static so that we don't keep seeding the rand    
private static readonly Random _random = new Random();
static DateTime CalculateDob(int youngestAge, int oldestAge)
{

    int age = 0;
    age = _random.Next(70, 105);
    var today = DateTime.Now;
    var year = today.Year - age;
    var month = _random.Next(1, 12);
    //Age might less than youngest age,
    //if born at/after current month, edge condition
    if (month >= today.Month)
    {
        month = today.Month - 1;
        if (month < 1)
        {
            year--;
            month = 12;
        }
    }
    var day = _random.Next(1, DateTime.DaysInMonth(year, month));
    return new DateTime(year, month, day);
}

最新更新