Forum Discussion

Punith_8's avatar
Punith_8
Occasional Contributor
9 years ago
Solved

Calculating days to a date

Hi,

 

I have a scenario where I need to add days which is stored in a variable to a date(YYYY-MM-DD) which again is stored in a variable. The way I try to add, it is concatenating with the date and not adding the days. Below is an example code.

 

import groovy.time.TimeCategory

 

use (TimeCategory){
def a= b+ c.days
log.info a
}

 

I am getting the output as 2015-09-2916 days instead of 2015-11-13

 

Thanks for the help!

  • nmrao's avatar
    nmrao
    9 years ago

    Does the below helps?

     

    import groovy.time.TimeCategory
    def pattern = 'yyyy-MM-dd'
    def dateString = '2015-09-29 17:31:54.5454000 -04:00'
    def b = new Date().parse(pattern,dateString)
    def c = 16  
    use (TimeCategory){   
        def a= b+ c.days   
        println a.format(pattern)
    }

4 Replies

  • nmrao's avatar
    nmrao
    Champion Level 3

    Check this out and see

     

    import groovy.time.TimeCategory
    def b = new Date()
    def c = 16
    
    use (TimeCategory){
      def a= b+ c.days
      println a.format('yyyy-MM-dd')
    }

    Output will be

     

    2015-11-12
    • Punith_8's avatar
      Punith_8
      Occasional Contributor

      Hi,

       

      Thanks for your reply. The code which you have provided works absolutely fine if the date is a new Date().

      But I am pulling a date from database through query and storing it in a variable. Like this, date = it[0]

       

      log.info date would print '2015-09-29 17:31:54.5454000 -04:00'

      def sum = 16

       def a = date + sum.days

       

      I don't get what I intend. I feel the date variable should be declared in a different way?

       

      • nmrao's avatar
        nmrao
        Champion Level 3

        Does the below helps?

         

        import groovy.time.TimeCategory
        def pattern = 'yyyy-MM-dd'
        def dateString = '2015-09-29 17:31:54.5454000 -04:00'
        def b = new Date().parse(pattern,dateString)
        def c = 16  
        use (TimeCategory){   
            def a= b+ c.days   
            println a.format(pattern)
        }