How do I calculate actions done per minute with Java? [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I'm writting a own application to help RuneScape 3 streamers educate their viewers with a DPS Rotation showing, and i'm wanting to implement a feature A.K.A APM (Which means Actions per minute) which is in other words, number of Keys (hotkeys) pressed within a minute, what i'm doing atm is, having a LocalTime when the thread starts, and every 5 secs it should show APM, but I guess my formula isn't correct.
Current formula is:
LocalTime apm = Main.keysPressed.size() / (LocalTime.now().minus(Main.apmLocalTime);
Which is:
counter / (current_time - start_time)
Problem is, the .minus() asks for a TemporalUnit as parameter, and i'm quite lost.
Can someone plz help me getting the formula.

tl;dr
actionsCount / Duration.between( start , Instant.now() ).toMinutes()
java.time.Instant
Use Instant to track a moment, not LocalTime.
Instant represents a moment, a point on the timeline, as seen in UTC. The class resolves to nanoseconds, but current conventional hardware clocks limit capturing the current moment to microseconds or milliseconds.
The LocalTime class represents merely a time-of-day without the context of a date and time zone or offset-from-UTC. So this class cannot represent a moment.
Use Duration class for ease, and to make your code more self-documenting.
Instant start = Instant.now() ;
…
Duration elapsed = Duration.between( start , Instant.now() ) ;
long minutesElapsed = elapsed.toMinutes() ; // Get a count of whole minutes in total span of time.
long actionsPerMinute = ( actionsCount / minutesElapsed ) ;
Tip: While generally in Java we want to use the more general interfaces and superclasses rather than the more specific concrete classes, in java.time the opposite is true. In java.time we want to use the specific concrete classes, because the framework programmers told us so in the documentation. So if your IDE or compiler suggests a Temporal, for example, follow the Javadoc to see the list of implementing classes, such as Instant.

Related

Java 11 get current Microseconds?

I already read an answer about if it's possible in Java 8 to get the current microseconds and the answer was no, but is it possible now in Java11?
The solution by using System.nanoTime() * 1000 is too inefficient.
Note: The Goal is NOT to get the exact current time in nanoseconds (for example 12:00 PM), obviously that's not working like this.
I would appreciate any help :)
As before, Instant.now() uses the most accurate time source available to the system. Depending on the system, there may not be anything finer-grained than System.currentTimeMillis.
As mentioned in the comments, System.nanoTime() / 1000 can be used for measuring the time between values, but doesn't give you anything like "the current time" -- you can't tell from it, for example, whether or not it's 3:00 PM.
If you need to measure or calculate e.g. the time between events in your program, there is nothing that will do better for you than System.nanoTime.
The Answer by Wasserman is correct. Here are more thoughts.
Not real-time
You commented:
When you try to do a very exact scheduler
Conventional implementations of Java, and conventional computer hardware, are not “very exact” along the scale of nanosecond and microsecond that you seemed to be targeting.
For “very exact” scheduling, you would have to use special hardware with special software. Look for the buzzword real-time, such as real-time Java.
System.nanoTime()
You said:
The solution by using System.nanoTime() * 1000 is too inefficient. Note: The Goal is NOT to get the exact time in nanoseconds
Be aware that System.nanoTime() does not tell you the current time.
System.nanoTime() tells you the approximate amount of nanoseconds that have elapsed since some arbitrarily chosen moment. In some implementations of Java, that moment may have been when the JVM was launched, or when the computer was booted, or something else. But you cannot count on that origin, nor should you care about the origin.
Represent elapsed time using Duration class.
To capture elapsed time in Java for micro-benchmarking:
long start = System.nanoTime() ;
…
Duration elapsed = Duration.between( start , System.nanoTime() ) ;
You can interrogate the Duration for its parts such as nanoseconds, whole seconds, minutes, and hours.
You said:
System.nanoTime() * 1000 is too inefficient
You must have meant:
( start - System.nanoTime() ) / 1_000
… to get a count of elapsed microseconds.
And, no, dividing or multiplying integers is not “inefficient“. If you care about optimizing for integer division operations, you should not be using conventional Java on conventional hardware, as discussed in section above.
Instant.now()
If you want to capture elapsed time as seen by human clocks:
Instant start = Instant.now() ; // May be precise to milliseconds, microseconds, or such depending on your implementation of Java and your host computer hardware clock.
…
Instant end = Instant.now() ;
To represent that elapsed time unattached to the timeline, use Duration.
Duration elapsed = Duration.between( start , end ) ;
To represent that elapsed time attached to the timeline, write a class storing a pair of Instant objects.
record SpanOfTime ( Instant start , Instant end ) {}
Or better yet, add the ThreeTen-Extra library to your project. This library brings classes that add functionality to the built-in java.time classes. One of these is Interval, with handy comparison methods such as abuts, contains, encloses, overlaps, etc.

What (if anything) is the significance of "2007-12-03T10:15:30.00Z" in the Java date/time parse examples? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
I've noticed that the various Java time parse methods (such as ZonedDateTime.parse(...)) consistently use the relevant portions of 2007-12-03T10:15:30+01:00[Europe/Paris] as the example in their Javadocs (with the exception of Instant which uses UTC as the time zone).
Obtains an instance of ZonedDateTime from a text string such as 2007-12-03T10:15:30+01:00[Europe/Paris].
Class
Example
Instant
2007-12-03T10:15:30.00Z
LocalDate
2007-12-03
LocalDateTime
2007-12-03T10:15:30
LocalTime
10:15
MonthDay
--12-03
OffsetDateTime
2007-12-03T10:15:30+01:00
OffsetTime
10:15:30+01:00
Year
2007
YearMonth
2007-12
ZonedDateTime
2007-12-03T10:15:30+01:00[Europe/Paris]
I realize this might just be an arbitrary date, but I've found in the past that oftentime the example values have additional meaning that help my understanding of the overall domain, beyond being just an example.
Is there any particular significance to this datetime, and why was it chosen as the example parse value for the Java time API?
I'm looking specifically for something that can be backed up with something concrete (e.g. official implementation discussions or statements by those involved in the library creation).
No special meaning
No, there is no special meaning to that example date-time value. Date-time handling is tricky enough, do not distract yourself with such trivial detail.
Technical writers commonly work with the same example data across scenarios for consistency, to most easily make apparent the similarities and contrasts.
The value may have personal significance to the original author. But as Arvind Kumar Avinash commented, what matters here is the formats rather than the value.
2007-12-03T10:15:30.00Z is not really an ideal example. I would have chosen a day-of-month larger than 12 to distinguish from the month number. And I would have chosen an hour larger than 12 to make obvious the 24-hour clock (0-23).

How to parse duration format from duration in JAVA? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I have a duration format which is like 0DT3H10M. So need to know how to parse this kind of data.
I want 0 Days 3 Hours and 10 Minutes from 0DT3H10M
in a specific format.
We can manually parse it by a character which is working fine but is there any other way or library available for this in android/java?
Duration
I will guess that string represents a duration of three hours and ten minutes.
Unfortunately that string fails to comply with the ISO 8601 standard used by default in the java.time classes Duration and Period. The standard starts all such strings with a P. And the standard separates any years-months-days from any hours-minutes-seconds with a T. So your input of three hours and ten minutes would be PT3H10M.
You will need to parse the string with your own code. Then use the extracted values to set the value of a java.time.Duration object.
You may be able to get away with simply prepending a P to comply with the standard. I hesitate to recommend this only because you would need to see the range of possible values you might receive to verify this approach would work.
Duration.parse( "P" + "0DT3H10M" )
Tip: Educate the publisher of your input data about ISO 8601.

Working out time between 7am to 3:30pm - JAVA [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I've created this program to calculate the time between startWork and finishWork
but I cant seem to figure out how to calculate time...
This is my Interface.
Just wanting to know a way of approaching this calculation.
Thanks
Use the Duration class from java.time to represent your working time. Let Duration.between() do the calculation for you, passing two LocalTime or two ZonedDateTime objects to it as appropriate. The latter will take transitions to and from summer time (DST) into the calculation if such a transition happens during the working hours.
If the time is entered as for example 1530 or 3:30pm, define a DateTimeFormatter to parse it into LocalTime.
Duration objects can be summed using its plus method, so you can calculate the hourly and monthly working time and so on.
To format the working time into for example 8.5 (for 8 hours 30 minutes), use the toMinutes method, then convert to double before you divide by 60 (I would declare the constant 60 as final double minutesPerHour = TimeUnit.HOURS.toMinutes(1);).
java.time
java.time is the modern Java date and time API. It came out nearly 4 years ago to replace the outdated and poorly designed date and time classes from Java 1.0 and 1.1 from the last years of the previous millennium.
Link: Oracle Tutorial trail Date Time
Use java.time as suggested by Ole V.V.:
String time1 = "07:00:00";
String time2 = "15:30:12";
LocalTime t1 = LocalTime.parse(time1);
LocalTime t2 = LocalTime.parse(time2);
Duration diff = Duration.between(t1, t2);
System.out.println(diff.toString());
Prints:
PT8H30M12S

Converting duration to years in Java8 Date API?

I have a date in the far past.
I found out what the duration is between this date and now.
Now I would like to know - how much is this in years?
I came up withthis solution using Java8 API.
This is a monstrous solution, since I have to convert the duration to Days manually first, because there will be an UnsupportedTemporalTypeException otherwise - LocalDate.plus(SECONDS) is not supported for whatever reason.
Even if the compiler allows this call.
Is there a less verbous possibility to convert Duration to years?
LocalDate dateOne = LocalDate.of(1415, Month.JULY, 6);
Duration durationSinceGuss1 = Duration.between(LocalDateTime.of(dateOne, LocalTime.MIDNIGHT),LocalDateTime.now());
long yearsSinceGuss = ChronoUnit.YEARS.between(LocalDate.now(),
LocalDate.now().plus(
TimeUnit.SECONDS.toDays(
durationSinceGuss1.getSeconds()),
ChronoUnit.DAYS) );
/*
* ERROR -
* LocalDate.now().plus(durationSinceGuss1) causes an Exception.
* Seconds are not Supported for LocalDate.plus()!!!
* WHY OR WHY CAN'T JAVA DO WHAT COMPILER ALLOWS ME TO DO?
*/
//long yearsSinceGuss = ChronoUnit.YEARS.between(LocalDate.now(), LocalDate.now().plus(durationSinceGuss) );
/*
* ERROR -
* Still an exception!
* Even on explicitly converting duration to seconds.
* Everything like above. Seconds are just not allowed. Have to convert them manually first e.g. to Days?!
* WHY OR WHY CAN'T YOU CONVERT SECONDS TO DAYS OR SOMETHING AUTOMATICALLY, JAVA?
*/
//long yearsSinceGuss = ChronoUnit.YEARS.between(LocalDate.now(), LocalDate.now().plus(durationSinceGuss.getSeconds(), ChronoUnit.SECONDS) );
Have you tried using LocalDateTime or DateTime instead of LocalDate? By design, the latter does not support hours/minutes/seconds/etc, hence the UnsupportedTemporalTypeException when you try to add seconds to it.
For example, this works:
LocalDateTime dateOne = LocalDateTime.of(1415, Month.JULY, 6, 0, 0);
Duration durationSinceGuss1 = Duration.between(dateOne, LocalDateTime.now());
long yearsSinceGuss = ChronoUnit.YEARS.between(LocalDateTime.now(), LocalDateTime.now().plus(durationSinceGuss1) );
System.out.println(yearsSinceGuss); // prints 600
Although the accepted answer of #Matt Ball tries to be clever in usage of the Java-8-API, I would throw in following objection:
Your requirement is not exact because there is no way to exactly convert seconds to years.
Reasons are:
Most important: Months have different lengths in days (from 28 to 31).
Years have sometimes leap days (29th of February) which have impact on calculating year deltas, too.
Gregorian cut-over: You start with a year in 1415 which is far before first gregorian calendar reform which cancelled full ten days, in England even 11 days and in Russia more. And years in old Julian calendar have different leap year rules.
Historic dates are not defined down to second precision. Can you for example describe the instant/moment of the battle of Hastings? We don't even know the exact hour, just the day. Assuming midnight at start of day is already a rough and probably wrong assumption.
Timezone effects which have impact on the length of day (23h, 24h, 25h or even different other lengths).
Leap seconds (exotic)
And maybe the most important objection to your code:
I cannot imagine that the supplier of the date with year 1415 has got the intention to interprete such a date as gregorian date.
I understand the wish for conversion from seconds to years but it can only be an approximation whatever you choose as solution. So if you have years like 1415 I would just suggest following very simple approximation:
Duration d = ...;
int approximateYears = (int) (d.toDays() / 365.2425);
For me, it is sufficient in historic context as long as we really want to use a second-based duration for such an use-case. It seems you cannot change the input you get from external sources (otherwise it would be a good idea to contact the duration supplier and ask if the count of days can be supplied instead). Anyway, you have to ask yourself what kind of year definition you want to apply.
Side notes:
Your complaint "WHY OR WHY CAN'T JAVA DO WHAT COMPILER ALLOWS ME TO DO?" does not match the character of new java.time-API.
You expect the API to be type-safe, but java.time (JSR-310) is not designed as type-safe and heavily relies on runtime-exceptions. The compiler will not help you with this API. Instead you have to consult the documentation in case of doubt if any given time unit is applicable on any given temporal type. You can find such an answer in the documentation of any concrete implementation of Temporal.isSupported(TemporalUnit). Anyway, the wish for compile-safety is understandable (and I have myself done my best to implement my own time library Time4J as type-safe) but the design of JSR-310 is already set in stone.
There is also a subtile pitfall if you apply a java.time.Duration on either LocalDateTime or Instant because the results are not exactly comparable (seconds of first type are defined on local timeline while seconds of Instant are defined on global timeline). So even if there is no runtime exception like in the accepted answer of #Matt Ball, we have to carefully consider if the result of such a calculation is reasonable and trustworthy.
Use Period to get the number of years between two LocalDate objects:
LocalDate before = LocalDate.of(1415, Month.JULY, 6);
LocalDate now = LocalDate.now();
Period period = Period.between(before, now);
int yearsPassed = period.getYears();
System.out.println(yearsPassed);

Categories

Resources