3

Trying to add 1 day to the simple date format.

import java.text.SimpleDateFormat 
Date date = new Date();
def dateformat =  new SimpleDateFormat("YYYY-MM-dd")
def currentDate = dateformat.format(date)
log.info "Current Date : " + currentDate

Date date1 = (Date)dateformat.parse(currentDate);
Calendar c1 = Calendar.getInstance();
c1.setTime(date1); 
log info c1.add(Calendar.Date,1);

Error occurred in line :

"log info c1.add(Calendar.Date,1);" groovy.lang.MissingPropertyException:No such property: info for class: Script16 error at line: 10

Note : The current date should be any date in future and i want to increment by 1 day.

Rao
  • 20,781
  • 11
  • 57
  • 77
rAJ
  • 1,295
  • 5
  • 31
  • 66
  • please check the solution to see if that helps. – Rao Dec 18 '17 at 14:13
  • Possible duplicate of [Incrementing date object by hours/minutes in Groovy](https://stackoverflow.com/questions/21166927/incrementing-date-object-by-hours-minutes-in-groovy) – tkruse Dec 20 '17 at 01:49

2 Answers2

2

You can use TimeCategory to add the day as shown below:

use(groovy.time.TimeCategory) {
  def tomorrow = new Date() + 1.day
  log.info tomorrow.format('yyyy-MM-dd')
}

EDIT: based on OP comments

Here is another away which is to add method dynamically, say nextDay() to Date class.

//Define the date format expected
def dateFormat = 'yyyy-MM-dd'

Date.metaClass.nextDay = {
   use(groovy.time.TimeCategory) {
      def nDay = delegate + 1.day
      nDay.format(dateFormat)
   }
}

//For any date
def dateString = '2017-12-14'
def date = Date.parse(dateFormat, dateString)
log.info date.nextDay()


//For current date
def date2 = new Date()
log.info date2.nextDay()

You may quickly the same online demo

Rao
  • 20,781
  • 11
  • 57
  • 77
  • This always gives me tomorrow date but i want whatever my date is, it should increment by 1 day. 'currentDate.next()' this works good. – rAJ Dec 18 '17 at 14:17
  • @rAJ, That is so simple you see above right? Instead of `new Date()` pass any date and just do `+ 1.day` as given in the answer to get the next day. – Rao Dec 18 '17 at 16:51
  • @rAJ, you may find the `EDIT` section more helpful as that is using a method for easiness `nextDay`. – Rao Dec 18 '17 at 17:46
  • Another option: Date newDate = use(groovy.time.TimeCategory) { previousDate + 1.day } – Glorious Kale Feb 04 '21 at 15:35
1

Well, the error you provide clearly tells you, that you have a syntax error. It says that there is no property info.

This is because you write

log info c1.add(Calendar.Date,1);

instead of

log.info c1.add(Calendar.Date,1);

If you would have used the correct syntax, it would complain that Calendar has no property Date.

So instead of

c1.add(Calendar.Date, 1)

you meant

c1.add(Calendar.DAY_OF_MONTH, 1)

But in Groovy you can even make it easier, using

c1 = c1.next()
Vampire
  • 35,631
  • 4
  • 76
  • 102
  • Checked when fresh date start. It displayed colon sign at the end. e.g : '2017-12-1:' – rAJ Dec 18 '17 at 18:59