I want to write Java code in Jmeter to copy current date in a variable and use this variable in next request?



  • This is my code:

    package dateTime;
    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.time.LocalDate;
    import java.time.LocalDateTime;
    import java.time.format.DateTimeFormatter;
    import java.util.Calendar;
    import java.util.Date;
    
    public class GetCurrentDateTime {
    
        public static void main(String[] args) {
    
    
            LocalDate localDate = LocalDate.now();
           String date = DateTimeFormatter.ofPattern("yyyy/MM/dd").format(localDate);
            log.info("The date is "+date);
    vars.put("currentDate",date);
    
        }
    
    }
    

    I tried above code in beanshell, JSR223 pre-processor or post processor but not able to use it further.



  • If you're using Groovy as the language you can simplify your code to this one-liner:

    vars.put('currentDate', new Date().format('yyyy/MM/dd'))
    

    You can refer the generated value as ${currentDate} later on.

    See Date documentation of Groovy GDK for more information on available functions.

    Also be aware that you can achieve the same without having to write even a single line of code via __time() built-in function like:

    ${__time(yyyy/MM/dd,currentDate)}
    

    Demo:

    enter image description here



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2