I have been using selenium webdriver and chrome and logs recently. But any timestamp values are coming back in a weird date time stamp format. I've search all over, and I cannot figure what it is. Furthermore, other values besides timestamp (like requestId or walltime) are also in new unknown formats. What format is this and how can I get it into a normal (MM DD YYYY HH:MM:SS..) format?
timestamp was 2484894.662632 around June 23rd 2021, 10:53:23.118
timestamp was 2486019.900761 around June 23rd 2021, 11:12:01.277
timestamp was 2581839.545059 around June 24th 2021, 13:49:09.354
Example:
"requestId":"30432.634","timestamp":87693.142713,"type":"XHR","wallTime":1624556888.229531}
Code snippet:
LoggingPreferences logPrefs = new LoggingPreferences();
logPrefs.enable(LogType.BROWSER, Level.ALL);
logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
flavorCapability.setCapability("goog:loggingPrefs", logPrefs);
driver.manage().logs().get(LogType.PERFORMANCE).getAll();
There is two way to get the desired result:
1) Simple way:
LogEntries entries = driver.manage().logs().get(LogType.PERFORMANCE);
for(LogEntry entry: entries){
System.out.println(entry.getTimestamp());
System.out.println(entry.getLevel());
System.out.println(entry.getMessage());
System.out.println(entry.toJson());
System.out.println(new Date(entry.getTimestamp()));
}
2) Second way to do it:
import org.json.JSONException;
import org.json.JSONObject;
LogEntries logs = driver.manage().logs().get("performance");
for (Iterator<LogEntry> it = logs.iterator(); it.hasNext();) {
LogEntry entry = it.next();
try {
JSONObject json = new JSONObject(entry.getMessage());
JSONObject message = json.getJSONObject("message");
String method = message.getString("method");
System.out.println(method);
if (method != null && "Network.responseReceived".equals(method)) {
JSONObject params = message.getJSONObject("params");
JSONObject response = params.getJSONObject("response");
JSONObject headers = response.getJSONObject("headers");
String timestamp = headers.getString("date");
String url = response.getString("url");
int status = response.getInt("status");
System.out.println("Response = " + response);
System.out.println("URL = "+ url);
System.out.println("Status Code = "+ status);
System.out.println("headers: " + response.get("headers"));
System.out.println("Timestamp: " + timestamp);
}
} catch (JSONException e) {
System.out.println(e.getMessage());
}
}
Ref: https://chromedevtools.github.io/devtools-protocol/tot/Network/
Note: Please provide the exact requirement, what exactly you want to get?
Subtracting the timestamp as seconds from the 3 datetimes you got these stamps, I could deduce that the timestamp means number of seconds that have passed since 16:38:25 +- 5 sec on the 25th of May 2021. All three timestamps agree that this is the origin.
Don't ask me why the origin is at that time. Maybe the computer booted at that time, or some number overflowed and started from 0 again.
Related
I have a requirement to read data from rest API for each and every minute and save that data it into DB. I am facing some issue to implement the rest URL for the start date and end dates. As of now from the current date I am able to execute it, but when I specify the start date and end date then for every one minute in between the start date and end date I need to make a call to rest API.
Note : I am using #Scheduler annotation for this one.
Rest API URL is formed dynamically like below :
private Optional<String> buidURL() {
TimeZone timeZone = TimeZone.getTimeZone(Constants.TIME_ZONE);
Date d=DateUtils.addDays(new Date(), -1);
java.text.SimpleDateFormat format = new java.text.SimpleDateFormat(Constants.DATE_FORMAT);
format.setTimeZone(timeZone);
String jpQueryReqParam =appProperties.getRest().getReqParam();
String jpQuery = appProperties.getRest().getUri();
Optional<String> feed = null;
try {
feed = Optional.of(jpQuery + URLEncoder.encode(jpQueryReqParam.replace("$queryTimestamp", format.format(d)), StandardCharsets.UTF_8.toString()));
} catch (Exception e) {
logger.info("Error occured at buidURL() " + e);
}
return feed;
};
and then calling rest API :
Optional<String> uri = buidURLFromTo();
String url=uri.get();
ResponseEntity<String> feedResponse = restTemplate.exchange(url, HttpMethod.GET, getRequest(headers()), String.class);
Different behaviour of RRULE based on start time :
Hi, I am currently trying to write a cron to rrule convertor and encountered some issues with some particular rules.
For the following rule :
"FREQ=YEARLY;BYMONTH=1,2,3,4,5,6,7,8,9,10,11,12;BYMONTHDAY=1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;BYDAY=SU,MO,TU,WE,TH,FR,SA;BYHOUR=0,10,20;BYMINUTE=0"
The behaviour of the dates iterator iss different depending on what the start time specified is :
final String rule2 = "FREQ=YEARLY;BYMONTH=1,2,3,4,5,6,7,8,9,10,11,12;BYMONTHDAY=1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;BYDAY=SU,MO,TU,WE,TH,FR,SA;BYHOUR=0,10,20;BYMINUTE=0";
final Date startDate = new SimpleDateFormat("yyyy-MM-dd").parse("2019-10-01");
final Date startDate2 = new SimpleDateFormat("yyyy-MM-dd").parse("2019-12-01");
System.out.println("Biweekly Rule Date 1");
final List<Date> biweeklyStartDate1 = biweeklyDates(rule2, startDate, 100);
System.out.println("Biweekly Rule Date 1 Result Count " + biweeklyStartDate1.size());
System.out.println("Biweekly Rule Date 2");
final List<Date> biweeklyStartDate2 = biweeklyDates(rule2, startDate2, 100);
System.out.println("Biweekly Rule Date 2 Result Count " + biweeklyStartDate2.size());
private static List<Date> biweeklyDates(final String rule, final Date date, final int limit) {
final RecurrenceRuleScribe scribe = new RecurrenceRuleScribe();
final ParseContext context = new ParseContext();
context.setVersion(ICalVersion.V2_0);
final RecurrenceRule recurrenceRule = scribe.parseText("RRULE:" + rule,null, new ICalParameters(), context);
final DateIterator iterator = recurrenceRule.getDateIterator(date, TimeZone.getTimeZone("GMT"));
final List<Date> values = new ArrayList<>();
while (iterator.hasNext()) {
final Date next = iterator.next();
values.add(next);
System.out.println(new SimpleDateFormat("yyyy-MM-dd").format(next));
if (values.size() >= limit) {
break;
}
}
return values;
}
In this example I try to retrieve a 100 occurences using the same rule. The occurences returned differ based on start time specified.
The first date would return the expected 100 results, the second one would return a single invalid occurence, which seem to be the start date.
It seems to be caused by last month of the year, whn specifying another date with December, the same return seems to be returned.
Google-rfc-2445 has the same behaviour but ical4j and some other rrule evaluators from other languages were able to produce the expected results.
I am using GWT, java, iText to produce a PDF and want to reformat the date. However, this code, on the server side, results in the message "Connection failed" on the client side (there are no error messages in the log) and no output:
String storedName = " ";
DateTimeFormat sdf = DateTimeFormat.getFormat("dd-MM-yyyy");
for (final Transcript scoutNamesDescription : listymAwards) {
if (scoutNamesDescription.getSection().equals(storedName)){
table.addCell(" ");
}else{
storedName = scoutNamesDescription.getSection();
table.addCell(scoutNamesDescription.getSection());
}
table.addCell(scoutNamesDescription.getAwardName());
Date awardedDate = sdf.parse(scoutNamesDescription.getAwardedDate());
String awardedString = DateTimeFormat.getFormat("dd-MM-yyyy").format(awardedDate);
table.addCell(awardedString);
}
preface.add(table);
document.add(preface);
When I comment out the date reformatting this works.
I have tried replacing the reformatting with:
System.out.println(scoutNamesDescription.getAwardedDate());
formatedDate = StringUtils.substring(scoutNamesDescription.getAwardedDate(), 8, 2) +
StringUtils.substring(scoutNamesDescription.getAwardedDate(), 4, 4) +
StringUtils.substring(scoutNamesDescription.getAwardedDate(), 0, 2);
System.out.println(formatedDate);
And this also produces the same error between the two println.
Based on Andrei Volgin's reply I have the following:
String storedName = null;
DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");
DateFormat df2 = new SimpleDateFormat("dd-MM-yyyy");
for (final Transcript scoutNamesDescription : listymAwards) {
if (scoutNamesDescription.getSection().equals(storedName)){
table.addCell(" ");
}else{
storedName = scoutNamesDescription.getSection();
table.addCell(scoutNamesDescription.getSection());
}
table.addCell(scoutNamesDescription.getAwardName());
Date awardedDate = df1.parse(scoutNamesDescription.getAwardedDate());
String awardedString = df2.format(awardedDate);
table.addCell(awardedString);
}
preface.add(table);
document.add(preface);
}
You cannot use GWT code on the server side. And in this case there is no need.
Use standard Java tools for formatting dates:
Convert java.util.Date to String
I am pulling 2 time values (as strings) from an XML file using xpath, these values (for example) are as follows:
00:07
08:00
00:07 is equal to 7 minutes
08:00 means 8am, with no date associated or needed (that is handled elsewhere)
Each of these values is subject to change in each XML file that i read. What i am attempting to do is as follows:
I need to subtract or add (depending on the situation) the 7mins from the 8am and give me a hh:mm time (eg: 07:53 or 08:07) in a string that i can eventually output to CSV
Next i need to produce 2 additional strings, 1 min before and 1 min after (eg: 07:52 and 07:54 OR 08:06 and 08:08) which also need to be output to CSV
I have tried everything and i can think of in relation to the time interpretation and manipulation to get the minutes subtracted/added to the time and then +/- 1 min from there, but being a complete novice i am totally stuck despite reading and testing as much as i could find. Spent the last 2 days working with Joda Time for the first time but i must be missing something fundamental as i cannot get the desired result with this either.
The question is - how can i achieve this?
Some sample code that gets me reading from the XML and printing the time
FileInputStream file = null;
try {
file = new FileInputStream(new File("Output/XmlConfig.xml"));
} catch (FileNotFoundException ex) {
Logger.getLogger(KATT.class.getName()).log(Level.SEVERE, null, ex);
}
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = null;
try {
builder = builderFactory.newDocumentBuilder();
} catch (ParserConfigurationException ex) {
Logger.getLogger(KATT.class.getName()).log(Level.SEVERE, null, ex);
}
Document xmlDocument = null;
try {
xmlDocument = builder.parse(file);
} catch (SAXException ex) {
Logger.getLogger(KATT.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(KATT.class.getName()).log(Level.SEVERE, null, ex);
}
XPath xPath = XPathFactory.newInstance().newXPath();
//get In Early rule from XML
String exceptionInEarlyXML = "Root/Response/WSAExceptionRule/#InEarly";
NodeList nodeListInEarly = null;
try {
nodeListInEarly = (NodeList) xPath.compile(exceptionInEarlyXML).evaluate(xmlDocument, XPathConstants.NODESET);
} catch (XPathExpressionException ex) {
Logger.getLogger(KATT.class.getName()).log(Level.SEVERE, null, ex);
}
String exceptionInEarly = (nodeListInEarly.item(1).getFirstChild().getNodeValue());
String InEarly = exceptionInEarly;
SimpleDateFormat format = new SimpleDateFormat("hh:mm");
Date d2 = null;
try {
d2 = format.parse(InEarly);
} catch (ParseException ex) {
Logger.getLogger(KATT.class.getName()).log(Level.SEVERE, null, ex);
}
DateTime dt2 = new DateTime(d2);
System.out.println(dt2);
This give me an output of 1970-01-01T00:07:00.000+10:00
I have tried so many permutations of code that i am at the point of deleting and starting again from scratch as it is un-compilable, and i am not experienced enough yet to be able to solve this issue.
Once you have the Date object for the parsed time, use getTime() to get the time in milliseconds and save it into a long variables. Then parse the offset time format and use a NumberFormat to get the number of minutes to offset. Add or subtract as needed. Take the result and create a new Date(millis) then apply your format to it.
Here is a working example:
String sTime = "08:00";
String sOffset ="00:07";
SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm");
Date dtTime = null;
try {
dtTime = dateFormat.parse(sTime);
} catch (ParseException e) {
// handle exception
return;
}
String[] offsetHrsMins = null;
NumberFormat numberFormat = NumberFormat.getNumberInstance();
long offsetMillis = 0;
try {
offsetHrsMins = sOffset.split(":");
long offsetHrs = (Long) numberFormat.parse(offsetHrsMins[0]);
long offsetMins = (Long) numberFormat.parse(offsetHrsMins[1]);
offsetMillis = 1000 * 60 * ((offsetHrs * 60) + offsetMins);
} catch (ParseException e) {
// handle exception
return;
}
long lTime = dtTime.getTime();
System.out.println("Adding minutes: " + dateFormat.format(new Date(lTime + offsetMillis)));
System.out.println("Subtracting minutes: " + dateFormat.format(new Date(lTime - offsetMillis)));
output:
Adding minutes: 08:07
Subtracting minutes: 07:53
First, you need to use SimpleDateFormat to parse the Date String to a Java.util.Date Object.
Second, After getting the Date Object, you can easily add/substract some time, and get another Date Object.
Last, you can use another SimpleDateFormat object to format the Date Object you got in second step to String.
SimpleDateFormat is very useful in Processing Date Strings. You can refer to the Javadoc in JDK or search some examples by Google.
Try passing the strings into a method aswel as what you are subrtacting by
Then converting them to ints
Then have an if statment that if the subtraction amount is greater that the minets int
then it subtracts 1 from the hours int and sets the new minets int to 60 subtract the subtraction int
Then convert them back to Strings
Here is the code exept for turing it back into a string
public class Main {
static String hours="8";
static String minets="7";
static String minus="17";
public static void main(String[] args) {
Main m = new Main();
m.timechange(hours,minets,minus);
}
void timechange(String hour, String minuet, String subtract){
int h = Integer.parseInt(hour);
int m = Integer.parseInt(minuet);
int s = Integer.parseInt(subtract);
if(s>m){
h-=1;
m=60-s;
}
else{
m-=s;
}
if ((m>9)&&(h>9)) {
System.out.println(h+":"+m);
} else {if ((m<10)&&(h<10)) {
System.out.println("0"+h+":0"+m);
}else {if ((m<10)&&(h>9)) {
System.out.println(h+":0"+m);
}else {if ((m>9)&&(h<10)) {
System.out.println("0"+h+":"+m);
}
}
}
}
}}
I wasnt sure if you wanted the back to String.
Hopeful that answers your question
The same can be done for when the minets reach over 60 if that ever happens.
Here a genuine Joda-Time answer because OP wants Joda-Time (and I also consider that library as superior to java.util.Date, java.text.SimpleDateFormat etc.):
Joda-Time has the big advantage of having several different temporal types. The right type for handling plain wall times is LocalTime. It also defines a method to add minutes.
Your task:
I need to subtract or add (depending on the situation) the 7mins from the 8am and give me a hh:mm time (eg: 07:53 or 08:07) in a string that i can eventually output to CSV
Next i need to produce 2 additional strings, 1 min before and 1 min after (eg: 07:52 and 07:54 OR 08:06 and 08:08) which also need to be output to CSV
The solution (only for part one, the other part is very similar):
LocalTime time = new LocalTime(8, 0); // corresponds to 08:00
LocalTime laterBy8Minutes = time.plusMinutes(7);
LocalTime earlierBy8Minutes = time.minusMinutes(7);
String sLaterBy8Minutes = laterBy8Minutes.toString("HH:mm"); // 08:07
String sEarlierBy8Minutes = earlierBy8Minutes.toString("HH:mm"); // 07:53
One additional note: If you start with another type like java.util.Date and wish to convert it to LocalTime then you can use the constructor
new LocalTime(jdkDate, DateTimeZone.forID("Europe/Moscow")) // example
or for default timezone:
new LocalTime(jdkDate)
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a table in which I've assigned burst time for each of machines in the form of time type in second for eg: 00:00:03, 00:00:02 etc.
I have a JAVA code that retrieves these burst times from the database and store it in a list and then convert each burst time into "milliseconds" type.
ArrayList<String>list22=new ArrayList<String>();
ResultSet rs = stmt1
.executeQuery("SELECT burst_time FROM virtual_machine WHERE VM_id <= 4");
while (rs.next()) {
list22.add(rs.getString("burst_time"));
}
String tempStamp = list22.get(0);
int i;
for(i=0;i<=list22.size()-1;i++){
System.out.println(list22.get(i));
}
for(String startstamp : list22){
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
formatter.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
java.util.Date d = null;
try
{
d = formatter.parse(startstamp);}
catch (java.text.ParseException e) {
System.err.println("Error: " + e.getMessage());
}
long qtm= d.getTime();
System.out.println(qtm);
}
This gives me the following result:
00:00:03
00:00:02
00:00:02
00:00:03
3000
2000
2000
3000
Now I need to store those milliseconds values in an array bur[] and use it in the program so that the corresponding machines should run for the assigned time which is stored in the array.
And can u please tell me whether I'm going through the right path in case of storing the milliseconds in array and giving it to the machines.
Following solution is nearly identical to the answer of #nikis, but preserves the important timezone setting. Otherwise users will get a surprising experience if this code runs in UK (Europe/London) because in year 1970 there was summer time - resulting in duration longs with one full hour too much:
long[] bur = new long[list22.size()];
for(int i=0; i < list22.size(); i++) {
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
// important, but avoid deprecated Etc/GMT-notation
formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
try
{
java.util.Date d = formatter.parse(list22.get(i));
long qtm= d.getTime();
bur[i] = qtm;
System.out.println(qtm);
} catch (java.text.ParseException e) {
System.err.println("Error: " + e.getMessage());
}
}
Hereby I have presented a workaround for an unsupported handling of durations in JDK pre 8. The truth is that SimpleDateFormat is designed to parse points in time, but not durations. Therefore it is so important to have a fixed starting point which never changes, hence the choice of UTC time zone and the reference point 1970-01-01T00:00:00,000Z (elapsed milliseconds since UNIX epoch).
JodaTime offers a specialized PeriodFormatter which really yields a org.joda.time.Period. Else it is possible to write your own specialized string parser (by help of substring(), indexOf() etc.) to factor out the integer parts and then to use Integer.valueOf(String) and then to calculate a long using this simple formula: (hour * 3600 + minute * 60 + second) * 1000.
I've modified your code to avoid NPE and also added bur[] array:
ArrayList<String>list22=new ArrayList<String>();
ResultSet rs = stmt1
.executeQuery("SELECT burst_time FROM virtual_machine WHERE VM_id <= 4");
while (rs.next()) {
list22.add(rs.getString("burst_time"));
}
for(int i=0;i<list22.size();i++){
System.out.println(list22.get(i));
}
long[] bur = new long[list22.size()];
for(int i=0;i<list22.size();i++){
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
try
{
java.util.Date d = formatter.parse(list22.get(i));
long qtm= d.getTime();
bur[i] = qtm;
System.out.println(qtm);
} catch (java.text.ParseException e) {
System.err.println("Error: " + e.getMessage());
}
}
Try this:
int bur[] = new int[list22.size()];
for(int i = 0; i < list22.size(); i++) {
String timeStamp = list22.get(i);
String s, m, h, split;
split = timeStamp.split(":");
h = split[0];
m = split[1];
s = split[2];
bur[i] = Integer.parseInt(s) * 1000 + Integer.parseInt(m) * 60000 + Integer.parseInt(h) * 3600000;
}
This solution doesn't use any date objects, since you won't need them in your case, if I'm not totally on the wrong way ;-)