joCha
joCha

Reputation: 378

Convert a jmeter variable of milliseconds to a formatted date

I cant seem to convert a date in milliseconds (1488520800000) extracted from JSON and put into a variable into a formatted date (2017-03-02). Here's my code:

import java.text.*;
import java.util.*;

SimpleDateFormat source = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
SimpleDateFormat target = new SimpleDateFormat("yyyy-MM-dd");
Date date = source.parse(vars.get("varReviewDatevalue"));
String newDate = target.format(date);
vars.put("varFormattedReviewdateValue",newDate);

Here's the error I get:

ERROR - jmeter.util.BeanShellInterpreter: Error invoking bsh method: eval       Sourced file: inline evaluation of: ``import java.text.*; import java.util.*;  log.info("value for variable:  14885208 . . . '' : Typed variable declaration : Method Invocation source.parse

What's weird is that I got similar code to work fine for an extracted date like: March 2, 2017. I can't figure out why the date represented in mills is not converting to a date. Any ideas?

Upvotes: 1

Views: 2578

Answers (1)

joCha
joCha

Reputation: 378

I was using the wrong jmeter element. This post helped me alot: JMeter: Converting extracted time stamp value to date format

I put this code into a JSR223 Sampler and everything worked

import java.text.*;
long timeStamp =  Long.parseLong(vars.get("varReviewDatevalue"));
Date date = new Date(timeStamp); 
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

TimeZone tzInAmerica = TimeZone.getTimeZone("America/Denver");
formatter.setTimeZone(tzInAmerica);
String dateFormatted = formatter.format(date);
vars.put("varFormattedReviewdateValue", dateFormatted); 
log.info(dateFormatted);
log.info(vars.get("varFormattedReviewdateValue"));

Upvotes: 1

Related Questions