Wildcards in Assertion on groovy-generated dates? - groovy

We are using SoapUI to test a Webservice of ours. This Webservice generates different Timestamps after a predictable pattern, so we use a groovy script to generate them on the SoapUI side and use these in assertions to assert the correct calculation on the webserver side. So far so good, it works like a charm on dates (pattern yyyy-MM-dd) and Timestamps with fixed hours / minutes (pattern yyyy-MM-dd'T'HH:mm':00.000'). We use variations of this script to do this, sometimes adding days, months, hours and so forth:
def sdf = new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")
Calendar instance = Calendar.getInstance();
instance.setTime(new Date());
Date date= instance.getTime();
s = sdf.format(date)
return s
===
Now I run into the following problem: This new project generates exact timestamps, down to the millisecond. Problem is, I cannot accuratly predict this, SoapUI generates the dates slightly earlier (thats no surprise, just a fact) than the webservice, and so there is a discrepancy of around 100 to 500 milliseconds between the timestamps.
I tried to add wildcards (*) (and enabled them, too) into this pattern to ignore the millisecond part, since it was deemed uneccessary as long as the second is right, but I guess they don't work within groovy scripts. Is there a way to make them work? Are there other approaches to check wether the timestamp down to the second is correct, and then ignore the milliseconds?

This is very easy! In a Script Assertion find the difference between the date you get back and "now", and assert that the difference is less than some tolerance.
def nowDate = new Date()
def sdf = new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX")
def currentDate = sdf.parse(context.expand('${getCurrentDateTime#ResponseAsXml#//*:current}'))
def minutesDiff = Math.abs(nowDate.getTime() - currentDate.getTime()) / 1000 / 60
assert minutesDiff < 5 : "Too great of a difference with server!"

Related

How can I get the current time in Godot?

I'm trying to make a digital clock in my game and need the current time (hours and minutes), formatted as so: HH:MM:SS How can I get the time necessary for this?
You can use the Time singleton, with the get_datetime_dict_from_system method to get the time dictionary from the current system time.
# Get the time dictionary
var time = Time.get_time_dict_from_system()
print(time) # {day:X, dst:False, hour:xx, minute:xx, month:xx, second:xx, weekday:x, year:xxxx}
In your case, to format it as HH:MM, you can use the less noisy function get_time_dict_from_system which only has hours, minutes, and seconds
var time = Time.get_time_dict_from_system()
# we can use format strings to pad it to a length of 2 with zeros, e.g. 01:20:12
print("%02d:%02d:%02d" % [time.hour, time.minute, time.second])
For older versions of Godot (-3.4), OS.get_time() also works but in 3.5+ it's deprecated and 4.x it's removed:

Convert String to Date format in andorid

I am getting the strings like 1604341549 and want to convert them to normal date format like
12 feb 2012 4:00. Here is my implementation
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
try {
Date d = sdf.parse(date);
sdf.applyPattern("dd MMM yyyy hh:mm");
holder.v.setText(sdf.format(d));
} catch (ParseException ex) {
Log.e("Exception", ex.getLocalizedMessage());
}
I have checked the logs and it is showing the dates as String before the try block but it is not implementing in the try block instead it is giving an error " Unparseable date: "1604341549" ".
Looks like your date is a long that encodes timestamp in seconds so you don't need to parse a String, instead you should simply build a Date object using Date(long date) constructor. don't forget to convert seconds to milliseconds by multiplying it by 1000
java.time through desugaring
Consider using java.time, the modern Java date and time API, for your date and time work. Let’s first declare two formatters, one for your input and one for your desired output.
/** For parsing seconds since the epoch */
private static final DateTimeFormatter unixTimestampFormatter
= new DateTimeFormatterBuilder()
.appendValue(ChronoField.INSTANT_SECONDS)
.toFormatter();
/** For formatting into normal date and time */
private static final DateTimeFormatter normalFormatter
= DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM)
.withLocale(Locale.UK);
Now the conversion goes like this:
String inputStr = "1604341549";
Instant inst = unixTimestampFormatter.parse(inputStr, Instant.FROM);
String normalDateTimeStr = inst.atZone(ZoneId.systemDefault())
.format(normalFormatter);
System.out.println(normalDateTimeStr);
Output is:
02-Nov-2020 19:25:49
I am convinced that Shamm is correct in the other answer: your input strings contain so-called Unix timestamps, that is, counts of seconds since the Unix epoch on Jan 1, 1970 at 00:00 UTC. With java.time we can build a formatter that parses such.
For giving “normal” output I am using Java’s built-in date and time format. In this case for UK locale, but you should use your users’ locale for most content users.
What went wrong in your code?
First, you were trying to parse the input string as containing year, month, date, hour, etc., which it didn’t. So you were lucky to get an exception so you got aware that it’s wrong (SimpleDateFormat very often does not give that, leaving you believing that everything is fine when it isn’t).
SimpleDateFormat parsed 1604 as year, 34 as month, 15 as day of month and 49 as hour of day. It then objected because there weren’t any digits left for the minutes (and seconds).
Question: Doesn’t java.time require Android API level 26?
java.time works nicely on both older and newer Android devices. It just requires at least Java 6.
In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
On older Android either use desugaring or the Android edition of ThreeTen Backport. It’s called ThreeTenABP. In the latter case make sure you import the date and time classes from org.threeten.bp with subpackages.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Unix time
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).
Java 8+ APIs available through desugaring
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.

Discord.py send dynamic time string

I'm currently working on a Bot where users can ask to play a game and set when to play it:
.play Valorant #30 -> "#anyone_who_is_playing_valorant, up for a round in 30 minutes?"
Currently, I'm editing the message every minute to display the correct time left, which unfortunately makes implementing other commands and functions way more difficult as it should be (while loop etc).
My only solution would be to display the time at which 30 minutes would be passed:
Message written at 17:00 -> "#anyone_who_is_playing_valorant, up for a round at 17:30?"
but due to timezones the displayed timestring has to be different for each user.
Actually, Discord supports such a function for embeds, but I haven't found a standart support for sending dynamic timestrings. I would imagine it to be like Pings, where there is no function but a syntax for it: <#!authorid>
Is there a way to send dynamic timestrings?
There is no dynamic time syntax in Discord messaging, the only such functionality is the timestamp in embeds as you mentioned.
Actually there is a way to have a dynamic string in your message but it does not work for the footer in the embed.
You only need to make a unix code,
from datetime import datetime
import calendar
date = datetime.utcnow()
utc_time = calendar.timegm(date.utctimetuple())
print(utc_time)
your output looks something like this: 1657723929
You format the code to this: <t:unixcode:R>
and it gives you
7 minutes ago
You can also make a timestamp which leads to the future with just adding the secconds to the unix code you just made e.g.:
this code <t:2665824929:R> represents
in 32 years
depends on when you see this because its dynamic

why is output of date function on node.js server wrong?

When date was 2018-03-21 19:40, i tried following code
var date = new Date();
console.log(date);
Output :
2018-03-21T16:40:53.755Z
Server is missing for 3 hours as you see. I fixed it by adding 3 hours but I think it's not a good way. How can i fix this problem with better way ?
I don't think the date is incorrect, if you look closely at the format it is being printed, it has a Z at the end, which means:
A suffix which, when applied to a time, denotes a UTC offset of 00:00;
often spoken "Zulu" from the ICAO phonetic alphabet representation of
the letter "Z".
I guess you are in a place separated by 3 hours from UTC.
Node.js uses this format to print Date objects by default, but you can print your local time using toLocaleString():
console.log(date.toLocaleString());
Your server is most likely in another time zone.

Groovy Script set timezone for timestamp

I've been struggling to set the Time zone inside a GroovyScript. By now I have found out that the following code returns the actual time stamp from my location.
javax.xml.datatype.DatatypeFactory.newInstance()
.newXMLGregorianCalendar( GregorianCalendar.getInstance() ).toString()[0..21] + "Z"
Now I need it to return the date and time in UTC specifically, so it has the main server's timezone and could be run from any other location.
All these are run in a GroovyScript test step in SoapUi and it will be used as a variable inside a WSDL request.
Note: This will be used as a single liner in the Custom Properties of a Soap Project.
One of the solution:
System.setProperty('user.timezone', 'UTC')
def gc= new GregorianCalendar()
the second is:
c = Calendar.instance
c.timeZone = TimeZone.getTimeZone("UTC")
The first solution work with a GregorianCalanedar which easy to convert to xml date. But I think best solution work with Calendar.
I don't test these codes! Please check it!

Resources