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
Related
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
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())
My intent is to set a condition to true only during a period.
The java.time.* API looked what I need.
import java.time.Period
import java.time.LocalTime
import java.time.Instant
import java.time.Duration
// java.time.Period
LocalTime start = LocalTime.of(1, 20, 25, 1024);
LocalTime end = LocalTime.of(3, 22, 27, 1544);
Period period = Period.between(startDate, endDate);
// java.time.duration
Instant start = Instant.parse("2017-10-03T10:15:30.00Z")
Instant end = Instant.parse("2019-10-03T10:16:30.00Z")
Duration duration = Duration.between(start, end)
Instant now = Instant.now();
How to check that now is happening during the defined Period / Duration ?
I see no direct API.
Edit :
I found a way with java.time.Instant
// now, start and end are defined above
// if now is between start and end
if (now.isAfter(start) && now.isBefore(end)){
}
You are mistaken about what Period and Duration are.
They are distances (subtract beginning from ending). Period between 01/03/2018 and 01/10/2018 is exactly the same as in between 05/04/1990 and 05/11/1990, same thing for Duration. So that means nothing to ask something like "is 3rd january, 2018 in 3 months?"
First: a simple solution:
LocalTime start = LocalTime.of(1, 20, 25, 1024);
LocalTime end = LocalTime.of(3, 22, 27, 1544);
LocalTime now = LocalTime.now()
boolean nowIsInTimeWindow = !(now.isBefore(start) || now.isAfter(end));
The same pattern works with LocalDate and LocalDateTime.
Second: additional thoughts on your original post:
now will never happen "during" period or duration. Both are just amounts of time, like "two days" or "five minutes". They don't contain information about start or end.
I'd suggest to not mix Instant and LocalDate but to use LocalTime instead of Instant. Thus you're consistent with regard to timezone: The Local... types are by definition timezone agnostic.
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.
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.