I am trying to write a method which takes two java.util.Date
's as parameters and returns a random java.util.Date
between these two in Scala. However, I get the same dummy result each time. What is wrong with my code?
Note:
randomDateBetween(new Date(2017, 1, 1), new Date(2018, 1, 1))
returns Tue Jun 12 09:36:00 EET 3917
like all the time
Code:
def randomDateBetween( firstDate : Date, secondDate : Date) : Date =
{
val ratio = new Random().nextInt(100);
val difference = (secondDate.getTime - firstDate.getTime)
val surplusMillis = (difference * (ratio / 100.0)).asInstanceOf[Long]
val cal = Calendar.getInstance()
cal.setTimeInMillis(surplusMillis + firstDate.getTime)
return cal.getTime()
}
I fixed it guys, thank you anyway. Cause of the error was java.util.Date being deprecated. I changed my method call like this and it worked perfectly fine:
val date1 = Calendar.getInstance
val date2 = Calendar.getInstance
date1.set(2017, 1, 1)
date2.set(2018, 1, 1)
randomDateBetween(date1.getTime, date2.getTime)