Reputation: 410
How to prepare a groovy script in which the result a random date on the last day of the month. range up from 2022-03-31 to 2050-01-31
Example
Possibilities
2022-03-31
2022-04-30
2022-05-31
and so on.
Result 2022-04-30.
I will be grateful for your help
I try:
def date = new Date()
def formattedDate = date.format("yyyy-MM-dd")
def theValue = formattedDate
Upvotes: 1
Views: 158
Reputation: 171154
Another method for fun
import java.time.LocalDate
import java.time.YearMonth
import java.time.temporal.ChronoUnit
import java.time.temporal.TemporalAdjusters
import java.util.stream.Collector
import java.util.stream.Collectors
import java.util.stream.Stream
def start = YearMonth.parse("2022-03")
def end = YearMonth.parse("2050-01")
Stream.iterate(start, s -> s.plusMonths(1))
.limit(ChronoUnit.MONTHS.between(start, end) + 1)
.map(m -> m.atEndOfMonth())
.collect(Collectors.toList())
.shuffled()
.head()
Upvotes: 2
Reputation: 45339
This uses java.time.LocalDate
methods to add to the first date a number of days (up to the number of days between the two dates). It then shifts that to the end of the month:
import java.time.*
def r = new Random();
def start = LocalDate.parse("2022-03-31")
def end = LocalDate.parse("2050-01-31");
def randomEndDate = (start + r.nextInt((int) (end - start)))
.plusMonths(1).withDayOfMonth(1).minusDays(1);
Upvotes: 2