System.nanoTime() and other Time-Related Classes - java

Right now I'm making skills for characters and I wanted to add cooldowns, but I have no idea on how to set times but I think I got an idea on which variables it should have:
private long currentTime; <-- this is the actual cooldown
private long cooldownTime; <--- this is the time it must pass before its ready
private boolean onCooldown; <---- game uses this to check if its on cooldown
private long elapsed = System.nanoTime(); <-- this takes the exact time when a skill is used and is setOnCooldown.
So this are the basic variables but I have no idea at all on how I could set them, I got an update() method, a cast() method inside the game. Please senpais halps! Giving choco cookies for anyone willing to halps n.n

tl;dr
Instant.now()
.plus(
Duration.ofHours( 1 ).plusMinutes( 35 )
)
Details
Not quite sure of you Question, but you seem to want to track a span of time for "cool down", and apparently test when that time has passed.
Using java.time
The java.time classes in Java 8 and later include the Duration and Period classes to track a span of time unattached from the timeline.
Duration duration = Duration.ofHours( 1 ).plusMinutes( 35 );
Get the current moment in UTC with a resolution up to nanoseconds. In Java 8, the current moment is captured up to milliseconds. In Java 9, a new implementation of Clock captures the current moment in up to the full nanosecond resolution of the Instant class.
Instant now = Instant.now();
To determine the moment when that cool-down expires, apply the Duration to the Instant to generate another Instant.
Instant coolDownExpires = now.plus( duration );
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8 and SE 9 and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Related

find current Date and day after tomorrow's date in java

How to find current date in java. I found a lot but every time i got same command
Date d = new Date(); or something similar
Every such command returns a date of 1970 year.
I fail to understand, Whats the benefit of this getting a date of 1970 ?
Is there any way where i can get current time and add a second into it.
My real purpose is to convert a long value into Date and add a second in it.
5:40:12 should give me 5:40:13 after adding a second.
Any help would be appreciated as i am fed up getting 1970 date.
My real purpose is to convert a long value into Date and add a second in it. 5:40:12 should give me 5:40:13 after adding a second
The troublesome java.util.Date class is now legacy, supplanted by the java.time classes.
Instant.ofEpochMilli( yourLongIntegerGoesHere ) // A moment on the timeline in UTC represented a count of nanoseconds since the epoch of `1970-01-01T00:00:00Z`.
.atZone( ZoneId.of( "Pacific/Auckland" ) // Time zone for the region whose wall-clock time you want to see.
.plusSeconds( 1 )
.toLocalTime() // Extract just the time-of-day without date and without time zone.
.toString() // Generate a string representing the time-of-day value in standard ISO 8601 format.
05:40:13
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
Java.Util.Date class is deprecated, I would recommend using
Java.Util.Calendar instead.
If you're looking to add a second to Current date, try something like this:
Calendar currentTime = Calendar.getInstance(); // gets a calendar using the default time zone and locale.
calendar.add(currentTime.SECOND, 1);
System.out.println(currentTime.getTime());
BUT, the reason why you are receiving a 1970 date when using the Date class is because that class works with milliseconds, so you must multiply the long value by 1000 in order for it to convert to a date, here's an example.
Date currentDate = new Date( YourLongValue * 1000);

How to convert nanoseconds of uptime into a readable date time format

I have extracted accerometer data from a android wearable. While looking at the data i realised the timestamp is not unix covertable. After research i saw the timestamp was actually nanoseconds in uptime. My question is the same as Accelerometer SensorEvent timestamp. However due to me not knowing Java i dont know how convert it using the solutions provided. Is there any python ways i can convert the nanoseconds in uptime into a readable date time format? An example of the timestamp would be "45900482044637".
tl;dr
Duration.ofNanos ( 45_900_482_044_637L )
PT12H45M0.482044637S
java.time
Java 8 and later has a Duration class for this purpose, as part of the new java.time framework (see Tutorial). These new classes have nanosecond resolution (nine decimal places in fractional second). A Duration represents a span of time as a number of hours, minutes, and seconds.
Android currently does not use Java 8 technology, but there is a back-port of java.time to Java 6 & 7. Further adapted to Android in the ThreeTenABP project.
Note the L appended to numeric literal for a long. Also, underscores make lengthy numbers easier for humans to decipher.
long input = 45_900_482_044_637L;
Let's convert that number to a Duration object.
Duration duration = Duration.ofNanos ( input );
When we generate a String representation of that Duration object, we get a String formatted using the ISO 8601 standard. That standard uses the pattern PnYnMnDTnHnMnS where the P marks the beginning and the T separates years-months-days from the hours-minutes-seconds.
System.out.println ( "duration: " + duration );
The answer is twelve hours, forty-five minutes, and a fraction of a second.
duration: PT12H45M0.482044637S
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
To get the uptime in human-readable format in Python:
>>> from datetime import timedelta
>>> ns = 45900482044637
>>> print(timedelta(microseconds=round(ns, -3) // 1000))
12:45:00.482045
Use:
long millis = TimeUnit.MILLISECONDS.convert(nanosecond, TimeUnit.NANOSECONDS);
Date date = new Date(millis );
DateFormat formatter = new SimpleDateFormat("yyyy/MM/dd hh:mm aaa");
String dateFormatted = formatter.format(date);

Java Calendar giving wrong value after parsing month string

I know that Java month begins from 0 and we have to add an offset of 1 to it,but when I use the following code which has a CST time zone,I get value for february month as 6.
I am trying to convert month to its equivalent calendar value such as 1 for January and 2 for Feb and so on.
Calendar cal = Calendar.getInstance();
cal.setTime(new SimpleDateFormat("MMM").parse("FEB"));
int monthInt = cal.get(Calendar.MONTH) + 1;
System.out.println(monthInt);
But when I run it in a machine with time zone as Indian Standard Time(IST-GMT +5.30) I get the expected value as 2.
What is wrong here?Do I need to include any locale to my calendar.I am getting totally meaningless values for months with the above code.
You should instantiate your Calendar with appropriate locales:
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("IST"),Locale.US);
tl;dr
Month.JANUARY.getValue()
1
Wrong class
You are trying to represent a month using a class that represents a moment. Square peg, round hole.
But when I run it in a machine with time zone as Indian Standard Time(IST-GMT +5.30) I get the expected value as 2.
Again, this occurs because you used the wrong class, a class that represents a moment in the context of a time zone.
I know that Java month begins from 0
Again, you are using the wrong class. This crazy numbering is one of many reasons why the date-time classes bundled with the earliest versions of Java were supplanted by the java.time classes defined by JSR 310 and built into Java 8 and later. Do not use the legacy classes.
Month
The appropriate class for a month is Month. This modern java.time class has sane numbering, unlike the legacy date-time classes that you should avoid.
convert month to its equivalent calendar value such as 1 for January
Use the Month.JANUARY enum object. As for its number, 1-12 for January-December.
int monthNumber = Month.JANUARY.getValue() ;
1
But I suggest you avoid representing a month by a mere integer number. Instead, use Month enum objects throughout your codebase. This makes your code more self-documenting, ensures valid values, and provides type-safety.
Use this:
public void runMonthlyReport( Month month ) { … }
…instead of this:
public void runMonthlyReport( int monthNumber ) { … }
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Time for a particular object Date

Is there any method en Date or Calendar class to know the milliseconds remaining from the time of the query to a particular Date object?
I'm using Alarmmanager for reschedule the alarms and would be important for me.
The solucion that I have at the moment is get the milliseconds of the existing object and deduct the current milliseconds.
Any better solution?
Thanks!
If you want how many milliseconds two Date values differ by, that's really easy using Date.getTime:
long millisLeft = target.getTime() - now.getTime();
Yes, Just use the Calenda, This class can give you time in miiliseconds (if that is what you want. So in your case you can just subtract two seperate Calanders. by the way you might also must likly nalso need GregorianCalendar;
ie that is
Calendar timeStamp = new GregorianCalendar();
hope this helps
you can also see one of my projects that uses this at
http://be.net/HARO
see the progague project in java, mostly used in the device,state device, numerical device classes.
tl;dr
ChronoUnit.MILLISECONDS.between( // This enum object offers a method for calculated elapsed time in a particular granularity.
myJavaUtilDateStart.toInstant() , // Convert from legacy class (`java.util.Date`) to modern class (`java.time.Instant`).
myJavaUtilDateStop.toInstant()
) // Returns a long integer.
java.time
The modern approach uses the java.time classes.
Instant
The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction). This class replaces java.util.Date and java.sql.Timestamp.
Instant instant = Instant.now() ; // Capture current moment in UTC in up to nanosecond resolution.
ChronoUnit.MILLISECONDS
To calculate elapsed time as a count of milliseconds specifically, use ChronoUnit.MILLISECONDS enum object. Beware of data loss, as any microseconds or nanoseconds in the Instant objects will be ignored.
long millisElapsed = ChronoUnit.MILLISECONDS.between( startInstant , stopInstant ) ;
Duration
Java offers a couple classes for represent a span of time unattached to the timeline:
Period for years-months-days.
Duration for hours-minutes-seconds-fractionalSecond.
Example:
Duration d = Duration.between( startInstant , stopInstant ) ;
Generate a String in standard ISO 8601 format by calling Duration::toString.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Java Calendar add issue

I'm having an issue with the Java Calendar add() functionality. The give or take is used to provide a roundabout date for dates to depart on a travel site.
end.add(Calendar.DATE, Integer.parseInt(giveOrTake));
The code is above and the test condition I'm using is to choose 29/07/2012 as the date and 3 days give or take. According to the documentation this should come out as 01/08/2012 but it comes out at 01/07/2012.
I've checked giveOrTake when it's passed to the method and it's fine so I have no idea what is going on. I can hardcode the giveOrTake value and still get the error.
Works for me:
import java.util.*;
public class Test {
public static void main (String []args) {
Calendar calendar = Calendar.getInstance();
calendar.set(2012, Calendar.JULY, 29);
calendar.add(Calendar.DATE, 3);
System.out.println(calendar.getTime()); // August 1st
}
}
My guess is that you've got the month wrong before calling add - note how my call to set above uses 6 as the month, because the call uses 0-based month numbers.
Note that as per my comment on the question, you'd be much better off moving to Joda Time if you can...
You are using troublesome old date-time classes, now legacy, supplanted by the java.time classes.
Also, you are using a date-time object to represent a date-only value, a misfit.
Using java.time
The LocalDate class represents a date-only value without time-of-day and without time zone.
LocalDate ld = LocalDate.of( 2012 , 7 , 29 ) ;
LocalDate threeDaysLater = ld.plusDays( 3 );
ld.toString(): 2012-07-29
threeDaysLater.toString(): 2012-08-01
See code run live in IdeOne.com.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8 and SE 9 and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
It was an issue with the date format. It was set as yyyymmdd when it should have been 'yyyyMMdd'.

Categories