Search code examples
javascriptjmeter

How to remove the last few characters of an ISO date with JavaScript in jmeter?


I wanted to create a dynamic date variable in JMeter. Following responses in Jmeter - get current date and time I found that the following works:

${__javaScript(new Date(new Date().setMonth(new Date().getMonth()+6)).toISOString())}

It sets a value of this variable 6 months in the future. Perfect.

The problem is that the formatting I need this date to be is: 2024-03-21T10:10:10

But the above line results in: 2024-03-21T20:54:55.386Z

I need to get rid of the last few characters but I'm not sure how to handle that on one line.

Using substring or slice would be ideal but it doesn't work. The result is blank. I'm guessing that I'm using a wrong syntax. Thinking I can't use substring on a date, I tried to wrap it into a new String but that doesn't fix it either.

For example,

${__javaScript(new String(new Date(new Date().setMonth(new Date().getMonth()+6)).toISOString()).substring(0,18))}

What am I doing wrong here?

As a side note in case if anyone wants to suggest timeShift JMeter function, I can't upgrade my JMeter version just yet because of other reasons so I need to use what works in version 2.13. I'm hoping that there's a way to accomplish this by other means, for example with JavaScript.


UPDATE: Here is what I've finally figured out.

The following worked like a charm:

${__javaScript( new Date(new Date().setMonth(new Date().getMonth()+6)).toISOString().split('.')[0])}


Solution

  • Just use split and join:

    var date = new Date()
    var dateString = date.toISOString()
    var shortDate = dateString.split('.')[0]
    
    console.log(shortDate) // 2023-09-21T22:29:56