I am reading the measurements and I have 2 ISO time stamps.
Now using the JSON extractor, I have parsed the time into 2 variables namely "time1" and "time2"
Now I want to compare the time and decide which one is greater.
Sample time that I had parsed to the variables are like below,
time1: 2021-07-01T00:00:03Z
time2: 2021-07-01T00:00:02Z
Now I want to compare and print the value saying time1 is greater than time2 and the returned response is in descending order.
I tried the below snippet in JSR223:
String time1 = vars.get("time1");
String time2 = vars.get("time2");
OffsetDateTime created = OffsetDateTime.parse(time1);
OffsetDateTime updated = OffsetDateTime.parse(time2);
if (updated.isAfter(created)) {
System.out.println("PASSED");
} else {
System.out.println("FAILED");
}
Working example with import and using log.info
import java.time.OffsetDateTime;
String time1 = vars.get("time1");
String time2 = vars.get("time2");
OffsetDateTime created = OffsetDateTime.parse(time1);
OffsetDateTime updated = OffsetDateTime.parse(time2);
if (updated.isAfter(created)) {
log.info("PASSED");
} else {
log.info("FAILED");
}
Related
Currently I am trying to serialize the XMLGregorianCalendar with jackson XML to 2 different formats. One completely filled with date, time and timezone and one filled with only the date. The first one now works correctly and I will just get 2022-03-23T15:30:00.000+00:00 back. Only the second one which should only return the date gives back 2022-03-22T23:00:00.000+00:00 instead of 2022-03-23. I know that you can most likely change it inside the setDateFormat in the jackson config but am not sure how the configuration should look like. Currently the code that I have looks like this:
Jackson config:
val objectMapperXml: ObjectMapper = XmlMapper().apply {
enable(ToXmlGenerator.Feature.WRITE_XML_DECLARATION)
setAnnotationIntrospector(
AnnotationIntrospector.pair(
JakartaXmlBindAnnotationIntrospector(TypeFactory.defaultInstance()),
JacksonXmlAnnotationIntrospector(false)
)
)
disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE)
disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
setSerializationInclusion(JsonInclude.Include.NON_EMPTY)
}
XMLGregorianCalendar for the dateonly extension:
val ZonedDateTime.toXMLGregorianCalenderDaysOnly: XMLGregorianCalendar
get() {
val cal = GregorianCalendar.from(this)
return DatatypeFactory.newInstance().newXMLGregorianCalendar(cal).apply {
hour = DatatypeConstants.FIELD_UNDEFINED
minute = DatatypeConstants.FIELD_UNDEFINED
second = DatatypeConstants.FIELD_UNDEFINED
millisecond = DatatypeConstants.FIELD_UNDEFINED
timezone = DatatypeConstants.FIELD_UNDEFINED
}
}
For the XMLGregorianCalendar I put all the values that I don't want to see as UNDEFINED. How can I solve this serialization issue with jackson XML?
I have a date value in format "2021-07-14T13:00:00.000+0300" (or similar). I want to convert it to Date. In this case I have to traverse a loop of different formats and check if they fail.
import java.text.*
import java.util.*
val formats = listOf(
"yyyy-MM-dd'T'HH:mm:ss.SSSZ",
"dd.MM.yyyy, EEEE, HH:mm" // And many others.
)
val date = "2021-07-14T13:00:00.000+0300"
val locale = Locale.getDefault()
for (format in formats) {
try {
return SimpleDateFormat(format, locale).parse(date)
} catch (e: ParseException) {
}
}
// If nothing found, return current date.
return Date()
How to convert this for-loop to something like map? So that we can get the first value without exception?
val result = formats.map { ... }
Another option, while still using firstNotNullOfOrNull(), is to use parse() with a ParsePosition object whose properties you can safely ignore when combined with setLenient(false)*.
The advantage of the parse(String, ParsePosition) version over parse(String) is that it returns null when it can't parse the date, instead of throwing an error, so the try-catch overhead per iteration can be avoided.
Along with that, since you're defaulting to the current date if all formats fail, you can avoid the nullable Date type result with an Elvis op at the very end.
val result: Date = formats.firstNotNullOfOrNull { format ->
with (SimpleDateFormat(format, locale)) {
setLenient(false) // may not be required, see below
parse(date, ParsePosition(0)) // is null or Date
}
} ?: Date()
Btw, setLenient(false) may not be required because on v15, there's no leniency for SimpleDateFormat.parse() in the docs...but it does behave leniently. Setting it to true above or leaving it out, and parsing a date of "2021-07-14T53:00:00.000+0300" (note the '53') produced Fri Jul 16 02:00:00 UTC 2021. With no leniency, it produces null. The leniency is mentioned on the abstract base class DateFormat.parse(String, ParsePosition) but not for SimpleDateFormat.parse(String, ParsePosition).
So if you're expecting non-pattern-matching dates rather than invalid-but-pattern-matching dates, the above loop could be reduced to:
val result: Date = formats.firstNotNullOfOrNull { format ->
SimpleDateFormat(format, locale).parse(date, ParsePosition(0))
} ?: Date()
Use firstNotNullOfOrNull().
val result: Date? = formats.firstNotNullOfOrNull { format ->
try {
SimpleDateFormat(format, locale).parse(date)
} catch (e: ParseException) {
null
}
}
My mobile timezone was GMT+7, I have a code to convert a specific date time(GMT+0) to a specific timezone(GMT+3):
var strDate = "2020-07-10 04:00:00+0000"
var result: Date?
var dateFormatter = SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSZ")
dateFormatter.timeZone = TimeZone.getTimeZone("Asia/Jerusalem")
result = dateFormatter.parse(strDate)
The problem is result always return "Fri Jul 10 11:00:00 GMT+07:00 2020"
But I expected it will return date object "Fri Jul 10 07:00:00 GMT+03:00 2020", any idea what's wrong with my code?
It's recommended to use java.time and stop using java.util.Date, java.util.Calendar along with java.text.SimpleDateFormat because of problems like this one.
In your code, the target time zone is obviously not applied to the date but it isn't obvious why it isn't.
A different problem might be pattern you are using because your example String does not contain any unit of time smaller than seconds but the pattern tries to consider .SSS (which made the code fail in the Kotlin Playground).
Switch to java.time and handle this with modern classes, such as OffsetDateTime for parsing this String (it doesn't contain information about a specific time zone, just an offset of zero hours) and ZonedDateTime as the target object (this considers a real time zone which may have different offsets depending things like Daylight Saving Time).
You could do it like this:
import java.time.ZoneId
import java.time.ZonedDateTime
import java.time.OffsetDateTime
import java.time.format.DateTimeFormatter
fun main() {
// this example is in UTC (+0000 --> no offset / offset of 0 hours)
var strDate = "2020-07-10 04:00:00+0000"
// create a formatter that can parse Strings of this pattern
// ([] represents optional units to be parsed)
var dateFormatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss[.SSS]Z")
// and parse the String to an OffsetDateTime using this formatter
var resultOfParsing = OffsetDateTime.parse(strDate, dateFormatter)
// then print the parsed result
println(resultOfParsing)
// create the target time zone
var timeZone = ZoneId.of("Asia/Jerusalem")
// then use the target zone for a zone shift
var jerusalemTime: ZonedDateTime = resultOfParsing.atZoneSameInstant(timeZone)
// and print the result
println(jerusalemTime)
// you could use your formatter defined above for a differently formatted output, too
println(jerusalemTime.format(dateFormatter))
}
which outputs (including all intermediate results):
2020-07-10T04:00Z
2020-07-10T07:00+03:00[Asia/Jerusalem]
2020-07-10 07:00:00.000+0300
I'm trying to compare the date of videos on a webpage to today's date. If the difference between the two dates is more than X days, report back as false.
The videos on the webpage have a tag in them which uses the format yyyy-mm-dd
I've got a selector set up to find the videos const videoDate = Selector('OPTA-video').withAttribute('data-secondary-time')
Now how do I set a variable to today's date and compare the two? I'm completely stuck!
I was using Katalon Studio before and here's the groovy script that did the same job:
String videoDate = WebUI.getAttribute(findTestObject('OPTA-video'), 'data-secondary_time')
LocalDate todaysDate = LocalDate.now()
LocalDate videoDateParsed = LocalDate.parse(videoDate, dtf)
if (ChronoUnit.DAYS.between(videoDateParsed, todaysDate) > 1) {
KeywordUtil.markFailed('The videos are 2+ days old.')
} else {
KeywordUtil.logInfo('The videos are up to date.')
}
You can use the getAttribute TestCafe method to access an attribute value. Then, parse the attribute value into the JavaScript Date object:
String videoDate = Selector('OPTA-video').getAttribute('data-secondary-time');
Date videoDateParsed = Date.parse(videoDate);
Date todaysDate = Date.now()
...
In the following thread you can find how to compare Date objects.
This is one of the scripts that I am using.
//getting your XPath test value into a string
String ann_time =
WebUI.getText(findTestObject("ObjectRepository/navigateTOElement/announcements_date"))
//converting time to simple date format
SimpleDateFormat sdf = new SimpleDateFormat('HH:mm')
Date sdf_anntime = sdf.parse(new String(ann_time))
//getting Current time
SimpleDateFormat dateFormatGmt = new SimpleDateFormat('HH:mm')
dateFormatGmt.setTimeZone(TimeZone.getTimeZone('GMT'))
SimpleDateFormat dateFormatLocal = new SimpleDateFormat('HH:mm')
currDate = dateFormatLocal.parse(dateFormatGmt.format(new Date()))
// time gap in long format
long duration = currDate.getTime() - sdf_anntime.getTime()
//time gap to mins
long diffInMinutes = TimeUnit.MILLISECONDS.toMinutes(duration)
//compare time gap with globale variable
if (diffInMinutes < GlobalVariable.News_updated_time) {
log.logInfo("system is getting updated,last updated "+ diffInMinutes + "min ago")
} else {
CustomKeywords.'errorMessage.logFailed.markStepFailed'('from 1 h, system was not updated')
log.logInfo('from '+ diffInMinutes+ 'h, system was not updated')
}
i have a remote sql satabase, and i connect him by php with JSON.
I can get string and int data OK, but now i have a problem.... i have a datetime field on my SQL database, and i dont know how to get it with JSON into java.util.Date
this is the code i tryed, but it fails getting the Date correctly, it gives me an exception (java.lang.ClassCastException: java.lang.String)
code:
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++)
{
JSONObject json_data = jArray.getJSONObject(i);
positions.add(new Position(json_data.getString("latitude"), json_data.getString("longitude"), (Date)json_data.get("timestamp")));
}
You will have to fetch the string sent in the JSON data and parse that string with something like SimpleDateFormat.
In my projects I have used two different solutions.
Storing the Date not as Date but as long(milisecs since 1.1.1980). In Java you can get this with date.getTime(). There should also a methode in PHP. The get the Date Object in Java just pass the long value to the constructor(date= new Date(long_value)).
With this Method you may have problems when dates comes from different time zones.
Write the Date as a formatted Date String in the JSON. How you encode the Date is up to you. A short sample give below. see[1] for further infos.
To get the Date you need a SimpleDateFormater.
DateFormat df = new SimpleDateFormat("yyyy.MM.dd G 'at' HH:mm:ss z");
try
{
Date today = df.parse("2001.07.04 AD at 12:08:56 PDT");
System.out.println("Today = " + df.format(today));
}
catch (ParseException e)
{
e.printStackTrace();
}
[1]http://download.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html