0

I'm trying to get DateTime between a range and here is my code.

public static void randomDate(Datetime min, Datetime max) {
    System.debug(DateTime.newInstance(
        generateRandomFromRange(min.getTime(), max.getTime())
    ));
    
}

public static Long generateRandomFromRange(Long startNum, Long endNum){
    Long returnValue;
    Integer randomNumber = Integer.valueof((math.random() * 10));
    boolean addSubFlag= math.mod(randomNumber,2) == 0 ? true : false; 
    Long diffInRange = endNum-startNum;
    if(addSubFlag){
        if(diffInRange > 1)
            returnValue =startNum + randomNum;
        else
            returnValue =startNum;
    }else{
        if(diffInRange > 1)
            returnValue = endNum - randomNum;
        else
            returnValue =endNum;
    }
    return returnValue;
}

When I try to run this using CreateData.randomDate(Datetime.newInstance(2021, 1, 1, 00, 00, 00), Datetime.newInstance(2022, 1, 31, 23,59,59));, I get error as System.MathException: Integer overflow: 19598365020.

Here my requirement is, the user gives StartDateTime and EndDateTime, I need to pass this to my method and return a random dateTime in the range including start and end dateTimes.

Please let me know where am I going wrong and how can I fix this.

Thanks

1
  • 1
    I ran your code in anon apex but not getting any error.
    – compski
    Commented Jan 24, 2022 at 12:09

1 Answer 1

1

Sorry for the confusion. I found the solution.

I created a different method as below.

public static DateTime randomDate(Datetime min, Datetime max) { 
        Long t1 = min.millisecond();
        Long t2 = max.millisecond();
        return DateTime.newInstance(
            min.getTime() + Math.mod(Math.abs(Crypto.getRandomLong()), (long)(min.getTime()-max.getTime()))
        ); 
    } 

This is giving me the expected result.

Thanks

1
  • 1
    A slightly easier to understand version would be ``` public static DateTime randomDate(Datetime min, Datetime max) { Long delta = max.getTime() - min.getTime(); return DateTime.newInstance( min.getTime() + (Long)(Math.random() * delta) ); } ```
    – H Alves
    Commented Jan 24, 2022 at 16:18

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .