Wednesday, February 15, 2006

Formatted Date in JMeter / JavaScript - Solution 2

In another JMeter testing scenario, I wanted to set a user defined variable to a date string with the format "yyyymmddhhmmss". The solution below solved the problem of left-padding with zeros and getting all the formatting done in a single line.


${__javaScript(with(new Date()) X = getFullYear() + String(getMonth() + 101).substr(1) + String(getDate() + 100).substr(1) + String(getHours() + 100).substr(1) + String(getMinutes() + 100).substr(1) + String(getSeconds() + 100).substr(1), dateString)}

The uses of this kind of user variable include:



  1. Knowing exactly when a test was run for auditing

  2. Guaranteeing a unique string for things like new test usernames [note that I am writing regression tests which only run once. If you are running load tests, you will want to add String(getMilliseconds() + 1000).substr(1) to get unique string each pass]

  3. Having a string you can key off of, for example to clean up database entries you have made

No comments: