Forum Discussion

mpw83's avatar
mpw83
Contributor
5 years ago
Solved

How to add one month to a given date for Assertion

I want to assert a date from a response in JSON. 

Expected Value is ApplicationDate + One Month

Application date is like '2019-03-04'. So the Expected Date should be '2019-04-04' 

I know there are so many ways to do this by adding one month to the current system date. But how to add one month to a given date? Thanks 

  • Hi again,

     

    Something like this works for me:

     

    import java.time.*
    import java.time.format.*
    
    def initialDateString = "2019-03-31" // this should be extracted dynamically but for the purpose of this example I guess it's ok
    
    // Create a LocalDate object
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd")
    LocalDate date = LocalDate.parse(initialDateString, formatter)
    
    date = date.plusMonths(1) // Update the date
    def modifiedDateString = date.format(formatter) // Create a String in case you need to process this date further

    Let me know if I can help you further!

7 Replies

  • Lucian's avatar
    Lucian
    Community Hero

    Hey mpw83 ,

     

    I can help you with this. I have a question though... What does it mean to add a month?

     

    For instance, what would be the expected result for you if the application date were to be "2019-03-31"? (April has only 30 days so April 31th would be valid).

    • mpw83's avatar
      mpw83
      Contributor

      Lucian , Thanks for the reply, Actually adding a calendar month. 

      if the application date were to be "2019-03-31 then + one month date should be 2019-04-30

      if application date = 28/02/2019 then + one month date should be 28/03/2019

      if application date = 15/01/2019 then + one month date should be 15/02/2019 .. etc 

  • Lucian's avatar
    Lucian
    Community Hero

    Hi again,

     

    Something like this works for me:

     

    import java.time.*
    import java.time.format.*
    
    def initialDateString = "2019-03-31" // this should be extracted dynamically but for the purpose of this example I guess it's ok
    
    // Create a LocalDate object
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd")
    LocalDate date = LocalDate.parse(initialDateString, formatter)
    
    date = date.plusMonths(1) // Update the date
    def modifiedDateString = date.format(formatter) // Create a String in case you need to process this date further

    Let me know if I can help you further!