jmeterweekday

Jmeter:how to get a weekday from _RandomDate()


I'm using the jmeter __Randomdate() to generate a date and pass it to an API request. most of the time, the date generated are weekends.how to get only the weekdays?

I'm trying to use the __timeshift() if it is weekend, but the __time(EEE,) is giving the day for a current date not from a variable. Can someone help with this. thanks


Solution

  • None of JMeter's built-in test elements is not suitable for your requirement, you will need to go for i.e. JSR223 PreProcessor and calculate the date there using Groovy language.

    Example code would be something like:

    static def randomWeekdayDate(Date start, Date end) {
        def random = new Random()
        def cal = Calendar.getInstance()
        cal.setTime(start)
    
        def daysBetween = (long) ((end.time - start.time) / (24 * 60 * 60 * 1000))
        def randomDays
    
        while (true) {
            randomDays = random.nextInt((int) daysBetween + 1)
            cal.setTime(start)
            cal.add(Calendar.DAY_OF_MONTH, randomDays)
    
            int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK)
            if (dayOfWeek >= Calendar.MONDAY && dayOfWeek <= Calendar.FRIDAY) {
                break
            }
        }
    
        return cal.time
    }
    
    def start = new GregorianCalendar(2024, Calendar.JANUARY, 1).getTime()
    def end = new GregorianCalendar(2024, Calendar.DECEMBER, 31).getTime()
    
    def randomWeekday = randomWeekdayDate(start, end)
    
    vars.put('randomDate', randomWeekday as String)
    

    You will be able to refer generated value as ${randomDate} where required