在该月的最后一天生成一个随机日期

Generating a random date on the last day of the month

如何准备一个 groovy 脚本,其中结果是该月最后一天的随机日期。范围从 2022-03-31 到 2050-01-31

例子

Possibilities
2022-03-31
2022-04-30
2022-05-31
and so on.
Result 2022-04-30.

我会很感激你的帮助

我试试:

def date = new Date()
def formattedDate = date.format("yyyy-MM-dd")
def theValue =  formattedDate

这使用 java.time.LocalDate 方法向第一个日期添加天数(最多为两个日期之间的天数)。然后将其转移到月底:

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);

另一种娱乐方式

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()