How to subtarct 6 hours from time in beanshell - jmeter

I am saving response from my application using jmeter and i want to subtract 6 hours from that time using beanshell post processor.
String timeforrequest = vars.get("response time");
time we are receiving is in following format
"2013-10-26 09:36:00 AM "

You can use regular java code in a beanshell processor.
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
String inputDateString = vars.get("response time"); //in the format "2013-10-26 09:36:00 AM "
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd hh:mm:ss a ");
DateTime time = formatter.parseDateTime(inputDateString);
DateTime newtime = time.minusHours(6);
vars.put("newtime", newtime.toString());
You can download joda-time jar from m2 repository here.

Sample code:
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
String timeforrequest = vars.get("response time");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss a");
Date before = sdf.parse(timeforrequest);
Calendar cal = Calendar.getInstance();
cal.setTime(before);
cal.add(Calendar.HOUR, -6);
Date after = cal.getTime();
String newtimeforrequest = sdf.format(after);
log.info("\n\n" + newtimeforrequest + "\n");
Demo:
References:
SimpleDateFormat class JavaDoc - I cannot guarantee that code will work for all date and time values as format may be different for systems with clock starting with 0 and with 1, etc. You may have to amend my SimpleDateFormat pattern
Date and Calendar classes JavaDocs - for more information on methods used
How to Use BeanShell: JMeter's Favorite Built-in Component - for general information on using Beanshell scripting in JMeter tests.

Related

How to convert Time in JMeter in 24 Hr format, while using shiftTime function to convert IST to UTC format?

Actually I'm trying to to shift the time, the application I'm working on is in UTC and I'm working in IST.
I've used both BEAN Shell pre processor and shiftTime function
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
int AddSeconds= 00; //this variable needs to be customized as per your need
int AddMinutes= 392; //this variable needs to be customized as per your need
int AddHours= 00; //this variable needs to be customized as per your need
Date now = new Date();
Calendar c = Calendar.getInstance();
c.setTime(now);
c.add(Calendar.SECOND, AddSeconds);
c.add(Calendar.MINUTE, AddMinutes);
c.add(Calendar.HOUR, AddHours);
Date NewTime = c.getTime();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
String mytime = df.format(NewTime);
vars.put("NewTime",mytime);
Shift Time :
"${__timeShift(yyyy-MM-dd'T'HH:mm:ss.SSS'Z',,PT393M,,)}"
Bun when I run the HTTP Request in Jmeter the time format is coming in 12Hrs only instead of 24 Hr
Also Time shift is taking in weird manner, I've tried all options from Stackoverflow from last 2 days and unable to achieve my task to convert IST to UTC.
This is what I'm using in Jmeter Post body
enter image description here
And this is what I'm getting as result
enter image description here
Time formats are getting totally mismatched here, can someone please help me to convert IST to UTC correctly while playing with these time formats and functions.
I don't think you can use __timeShift() function for getting the date in the different timezone, it will return you the current (default) one
So if you need to add 392 minutes to the current time in the time zone different from yours - you will have to go for __groovy() function and use TimeCategory class
Example code:
${__groovy(def now = new Date(); use(groovy.time.TimeCategory) { def nowPlusOneYear = now + 392.minute; return nowPlusOneYear.format("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"\,TimeZone.getTimeZone('IST')) },)}
Demo:
If you need to get the time in UTC just change IST to UTC
${__groovy(def now = new Date(); use(groovy.time.TimeCategory) { def nowPlusOneYear = now + 392.minute; return nowPlusOneYear.format("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"\,TimeZone.getTimeZone('UTC')) },)}
More information: Creating and Testing Dates in JMeter - Learn How
Also be informed that since JMeter 3.1 you're supposed to be using JSR223 Test Elements and Groovy language for scripting
Just adding one more way to do this via bean shell preprocessor and it worked for me pretty well.
Here is the code to use... here -325 minutes is the difference between IST and UTC
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
int AddSeconds= 00; //this variable needs to be customized as per your need
int AddMinutes= -325; //this variable needs to be customized as per your need
int AddHours= 00; //this variable needs to be customized as per your need
Date now = new Date();
Calendar c = Calendar.getInstance();
c.setTime(now);
c.add(Calendar.SECOND, AddSeconds);
c.add(Calendar.MINUTE, AddMinutes);
c.add(Calendar.HOUR, AddHours);
Date NewTime = c.getTime();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
String mytime = df.format(NewTime);
vars.put("NewTime",mytime);
// NewTime is your jmeter variable

Java 8 - SQL Timestamp to Instant with properly formatted time

I've read through the available q and a on SO, but nothing I have found answers my question of how to format my time in 12hour format.
Following is my code that runs a query on a MySQL database and returns results, checking to see if an appointment is within 15 minutes of login so an alert can pop.
public void apptCheck(int userId) throws SQLException {
// this method checks for an appointment occurring within 15 minutes of login
Statement apptStatement = DBQuery.getStatement();
String apptQuery = "Select apt.start, cs.customerName from DBName.appointment apt "
+ "JOIN DBName.customer cs ON cs.customerId = apt.customerId WHERE "
+ "userId = " + userId + " AND start >= NOW() AND start < NOW() + interval 16 minute";
apptStatement.execute(apptQuery);
ResultSet apptRs = apptStatement.getResultSet();
while(apptRs.next()) {
Timestamp apptTime = apptRs.getTimestamp("start");
ResourceBundle languageRB = ResourceBundle.getBundle("wgucms/RB", Locale.getDefault());
Alert apptCheck = new Alert(AlertType.INFORMATION);
apptCheck.setHeaderText(null);
apptCheck.setContentText(languageRB.getString("apptSoon") + " " + apptTime.toInstant().atZone(ZoneId.systemDefault()));
apptCheck.showAndWait();
}
My result is:
I want the time to display 3:00, not the 19:00 - 06:00. How can I make that happen?
ZonedDateTime zonedDateTime=ZonedDateTime.of(apptTime.toLocalDateTime(),ZoneId.systemDefault());
You can use ZonedDateTime and format the time as you want.
docs.oracle.com/javase/8/docs/api/java/time/ZonedDateTime.html ZonedDateTime has a lot of features you can see all here and you can get the hour, minute, day etc.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("hh:mm:ss");
String formattedString = zonedDateTime.format(formatter);
if you only want time in 12hour format you can use this
I found the solution which will perform the UTC to local time conversion and then format the time so that the resulting alert is in 12 hour time format without the date or time zone info. Here is the full code:
while(apptRs.next()) {
Timestamp apptTime = apptRs.getTimestamp("start");
// perform time conversion from UTC to User Local Time
ZoneId zidApptTime = ZoneId.systemDefault();
ZonedDateTime newZDTApptTime = apptTime.toLocalDateTime().atZone(ZoneId.of("UTC"));
ZonedDateTime convertedApptTime = newZDTApptTime.withZoneSameInstant(zidApptTime);
ResourceBundle languageRB = ResourceBundle.getBundle("wgucms/RB", Locale.getDefault());
Alert apptCheck = new Alert(AlertType.INFORMATION);
apptCheck.setHeaderText(null);
// set the Alert text and format in 12 hour format
apptCheck.setContentText(languageRB.getString("apptSoon") +
convertedApptTime.toInstant().atZone(ZoneId.systemDefault())
.format(DateTimeFormatter.ofPattern("h:mm a")) + ".");
apptCheck.showAndWait();
}

Handling offset naive object

I am trying to find the time until the next day according to IST. I am using pytz. I am not getting why "tomorrow" is offset naive while tomorrow is defined using offset aware constants.
I've tried printing stuff like print tomorrow_date - now , but that gives 0 and i do not know how is that happening.
from datetime import datetime,timedelta
from pytz import timezone
ist = timezone('Asia/Kolkata')
def get_until_tomorrow():
now = datetime.now(ist)
#today = date.today()
tomorrow_date = now + timedelta(days=1)
tomorrow = datetime.combine(tomorrow_date,time=time(00,00))
seconds_left = tomorrow - now
return seconds_left.seconds
print(get_until_tomorrow())
I am getting the error that I cannot subtract an offset naive and an offset aware object. now is an offset aware object because i set it so directly, but tomorrow is, according to it, an offset naive variable. How is this possible when i have used only offset aware variables to define tomorrow?
Looks like you have to make it offset aware by using localise. See if this helps.
from datetime import datetime,timedelta, time
from pytz import timezone
ist = timezone('Asia/Kolkata')
def get_until_tomorrow():
now = datetime.now(ist)
tomorrow_date = now + timedelta(days=1)
tomorrow = datetime.combine(tomorrow_date,time=time(00,00))
tomorrow = ist.localize(tomorrow)
seconds_left = tomorrow - now
return seconds_left.seconds
print(get_until_tomorrow())

Different week no. returned using DateTimeFormatter YYYY-w & by DateTimeFormatter.ISO_WEEK_DATE Java8

I am trying to format the milliseconds date from sample milliseconds value-1451646394000 to get the week number.
Following is the code snippet:
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.chrono.IsoChronology;
import java.time.format.DateTimeFormatter;
public class Test1 {
public static void main(String[] args) {
final String dateFormat = "YYYY-w";
ZoneId zoneId_UTC = ZoneId.of("UTC");
final long indexTimeStampMillis = 1463510726000L;
LocalDateTime dateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(indexTimeStampMillis), zoneId_UTC);
// Case 1:
final DateTimeFormatter weekFormatter = DateTimeFormatter.ISO_WEEK_DATE;
String output1 = dateTime.format(weekFormatter);
System.out.println("Correct output of week number according to ISO Week numbers" + output1);
// Case 2:
final DateTimeFormatter formatter = DateTimeFormatter.ofPattern(dateFormat).withZone(zoneId_UTC)
.withChronology(IsoChronology.INSTANCE);
String output = dateTime.format(formatter);
System.out.println("Week number I am getting in output " + output);
}
}
Output on console:
Correct output of week number according to ISO Week numbers2016-W20-2
Week number I am getting in output 2016-21
NOTE:
Correct week number for the above date is 20 according to ISO 8601. The date in milliseconds converts to Tue, 17 May 2016 18:45:26 GMT.

Using JodaTime to compare time without date

I'm trying to compare two times (in LocalTime format) in order to use them as part of an if statement. I have done some research but all I can find it for using date without time, not the other way around. I am trying to compare a time against the system time with the following code:
import org.joda.time.*;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.LocalDate;
LocalTime startTime2;
LocalTime airTime2;
LocalTime foamTime2;
LocalTime scTime22;
firstTime = airTime2;
secondTime = localTime;
return firstTime.compareTo(secondTime);
Which should return the larger value. toLocalTime does not seem to be supported by JodaTime, does anyone know what the alternative would be?
I had adapted the code from:
LocalDate firstDate = date1.toLocalDate();
LocalDate secondDate = date2.toLocalDate();
return firstDate.compareTo(secondDate);
It seems to work pretty straightforward (JodaTime 2.9.1):
import org.joda.time.LocalTime;
LocalTime earlier = new LocalTime("23:00:00");
LocalTime later = new LocalTime("23:12:34");
System.out.println(earlier.compareTo(later)); // -1
System.out.println(later.compareTo(earlier)); // 1
System.out.println(earlier.compareTo(earlier)); // 0

Resources