groovy date plus提供错误的日期

groovy date plus提供错误的日期,groovy,time,dateadd,Groovy,Time,Dateadd,我试图生成一个随机日期,然后再加上5天。它在大多数情况下运行良好,但当新日期进入明年时,结果实际上是回到同年年初。不知道为什么。。这是我的密码 Date today = new Date(); def endRange = 1500 def randomInterval = new Random().nextInt(endRange) startDate = today.plus(randomInterval) endDate= startDate.plus(5) 我在循环中运行了1000次,

我试图生成一个随机日期,然后再加上5天。它在大多数情况下运行良好,但当新日期进入明年时,结果实际上是回到同年年初。不知道为什么。。这是我的密码

Date today = new Date();
def endRange = 1500
def randomInterval = new Random().nextInt(endRange)
startDate = today.plus(randomInterval)
endDate= startDate.plus(5)
我在循环中运行了1000次,其中18次要么重新设置到同一年,要么增加一年。不知道为什么。下面是两个示例输出结果

startdate         enddate
2022-12-27   -- > 2022-01-01
2020-12-26  -- >  2021-12-31
谢谢你在这方面的帮助

//更新

经过一番挖掘,这是在我将日期格式更改为“YYYY-MM-dd”后发生的,然后再写入excel,因为这是我需要的格式。而且,在加上5天之后,它总是发生在任何一个延到明年的日期

Date today = new Date();
def minStart = today+5 //diff_currentDt_startDt
def endRange = 1500
def randomInterval = new Random().nextInt(endRange)
startDate = today.plus(randomInterval)
endDate= startDate.plus(diff_startDt_endDt)
// after this I format them and then write to excel
def startDate1=startDate.format('YYYY-MM-dd')
def endDate1=endDate.format('YYYY-MM-dd')
Label label1= new Label(0, i, startDate1)
sheet.addCell(label1)
Label label2= new Label(1, i, endDate1);
sheet.addCell(label2);
再次进一步检查,不知何故,格式弄乱了它。以下是格式化前后的日期

Tue Dec 24 19:31:02 EST 2019  //startdate
2019-12-24  // startdate in YYYY-MM-dd format
Sun Dec 29 19:31:02 EST 2019  // enddate (startdate +5)
2020-12-29 // enddate in YYYY-MM-dd format

我做错了什么?

看起来像是.format('YYYY-MM-dd')中的“YYYY”导致了它的问题,在将其更改为.format('YYYY-MM-dd')中的“YYYY”后,它就被修复了。

是否每次开始日期都是27/12/。。还是更大?我已经运行了您的1000次测试&没有复制您的结果,您的基本日期设置是什么?错误是随机的,还是您可以复制它?如果您可以复制它,那么请将代码添加到问题中,以显示实际问题。首先回答您的两个问题,经过一点挖掘,在我使用“.format('YYYY-MM-dd')格式化日期后,会发生这种情况,然后再写入excel,因为这是我需要的格式。更新主要问题。