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