如何使用 beanshell 采样器在 jmeter 中转换日期时间

How to convert datetime in jmeter using beanshell sampler

我的一个 http 采样器有以下格式的时间戳

Tue Nov 07 10:28:10 PST 2017

我需要将其转换为以下格式

11/07/2017 10:28:10

我尝试了不同的方法,但不知道我在做什么 wrong.Can 谁能帮助我 that.Thanks。

这与 how you'd do it in Java 非常相似。

这是一个例子:

import java.text.DateFormat;
import java.text.SimpleDateFormat;

String string = "Tue Nov 07 10:28:10 PST 2017";

// Original format to convert from
DateFormat formatFrom = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH);

// Target format to convert to
DateFormat formatTo = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss", Locale.ENGLISH);

// Parse original string, using original format
Date date = formatFrom.parse(string);

// Convert to a target format
String result = formatTo.format(date);

// Just to show the output, not really necessary
log.info(result);

一个问题:由于目标格式省略了区域,因此将使用计算机的本地区域。因此,例如原始时间 10:28:10 PST 对于 PST 区的计算机将转换为 10:28:10,但对于 EST 区的计算机,它将转换为 13:28:10

听说Groovy is the new black所以给出:

  1. Date class in Groovy SDK has format() and parse() 方法
  2. 建议使用JSR223 Test Elements and Groovy language since JMeter 3.1

您可以在一行 Groovy 代码中转换日期,例如:

Date.parse("EEE MMM dd HH:mm:ss zzz yyyy", 'Tue Nov 07 10:28:10 PST 2017').format("dd/MM/yyyy HH:mm:ss", TimeZone.getTimeZone('PST'))

演示: