Java Instant is a set of pre-defined methods in Java, which can be used in the code blocks for performing specific functions in the program. A few of the most commonly used Java Instant methods are toString(), parse(), ofEpochMilli(), getEpochSecond(), getNano(), plusMillis(long milliToAdd), plusNanos(long nanosToAdd), plusSeconds(long secondsToAdd), minusSeconds(long secondsToSubtract), minusMillis(long millisToSubtract), minusNanos(long nanosToSubtract), compareTo(Instant otherInstant), isAfter(Instant otherInstant), and isBefore(Instant otherInstant). This feature in Java is known for its higher efficiency, remarkable performance, reusability, optimized code length, etc.
Syntax
The Instant class provides multiple static factory methods to create the Instance of Instant class. The following are the static methods by which we can get Instance of Instant class with different standard values.
Start Your Free Software Development Course
Web development, programming languages, Software testing & others
Instant instant = Instant.now();
The method now() returns the current instant from the system clock. This instance represents the total number of nanoseconds from the start time or EPOCH. This is the time counted from the beginning of the 1st Jan 1970. This method to get the instant is useful for representing machine timestamp and will be used more frequently than others.
Instant instant = Instant.EPOCH;
This static field will return an Instance of Instant class representing the exact EPOCH time.
Instant instant = Instant.MAX;
This static field will return an Instance of Instant class representing the maximum value of the instance.
Instant instant = Instant.MIN;
This static field will return an Instance of Instant class representing the minimum value of instance, and the value is negative.
Methods of Java Instant
So here comes the main part or usage of Instant class. Following is the list of some of the main methods which belong to the Instant class.
- toString(): This method is overridden from the Object class to represent the Instance in string format by using ISO-8601 standard.
Below are the methods which can be used to get an instance of Instant class.
- parse(): This method takes a text string as an argument and returns an instance of an Instance class representing the same value passed. The string should be valid instant in UTC.
- ofEpochMilli(): This method takes input long (milliseconds) as an argument and returns an instance of an Instance class representing the same value passed. This method can be used to convert the java.util.Date object into Instant.
The instance of Instant class represents time with nanoseconds precision as compared to util.Date ( milliseconds precision ). Therefore, the instant requires more storage to store its value (larger than long). So, the instant class stores the second’s value in a long variable and the remaining nanoseconds value in the int variable. We can access these separate values using the below methods.
- getEpochSecond(): This method will simply return the seconds from EPOCH.
- getNano(): This method returns a number of nanoseconds from the time-line or the start of the second.
Below are the methods which can be used in instant manipulation or calculations.
- plusMillis(long millisToAdd): This method will add many milliseconds passed with the instant and return the new Instant.
- plusNanos(long nanosToAdd): Similar to the previous one but with an addition of Nanoseconds.
- plusSeconds(long secondsToAdd): The addition of seconds.
Similar methods exist for minus or subtraction operation. These methods will subtract the number of seconds passed from the instant and will return a new instant.
- minusSeconds(long secondsToSubtract)
- minusMillis(long millisToSubtract)
- minusNanos(long nanosToSubtract)
Below are the methods which can be used to compare the two instants,
- compareTo(Instant otherInstant): This method will compare the one instant with the passed one. Returns the integer value negative if it is less and positive if it is greater.
- isAfter(Instant otherInstant): This method checks if the passed instant is after the current instant. Returns true or false.
- isBefore(Instant otherInstant): Similar to the previous one, checks if the passed instant is before the current instant. Returns true or false.
Examples to Implement Java Instant
Below are the examples of implementing java instant:
1. toString()
Code:
import java.time.Instant; public class app { public static void main(String[] args) { Instant instant = Instant.now(); System.out.println( instant.toString() ); } }
Output:
The output will be the time of the system running the code.
2. getEpochSecond()
Code:
import java.time.Instant; public class app { public static void main(String[] args) { Instant instant = Instant.now(); System.out.println( instant.getEpochSecond() ); } }
Output:
3. getNano()
Code:
import java.time.Instant; public class app { public static void main(String[] args) { Instant instant = Instant.now(); System.out.println( instant.getNano() ); } }
Output:
4. plusSeconds()
Code:
import java.time.Instant; public class app { public static void main(String[] args) { Instant instant = Instant.now(); System.out.println( instant ); instant = instant.plusSeconds( 3600 ); System.out.println( instant ); } }
Output:
We have added exactly 3600 seconds, i.e. 1 hour, to the current instant, as it can be seen in the output that time is increased by 1 hour.
5. compareTo()
Code:
import java.time.Instant; public class app { public static void main(String[] args) { Instant instant = Instant.now(); System.out.println( instant ); Instant instant2 = instant.plusSeconds( 3600 ); System.out.println( instant.compareTo( instant2 ) ); } }
Output:
Here, we are comparing two instants, current with the instant having added 1 more hour. As the current instance is less than instance2, the output is negative.
Conclusion
So, we have seen the Instant class introduced from Java 8. This class represents the seconds from the start of the timeline with nanoseconds precision. This class is useful to generate the timestamp, which will represent the system time. We have seen different types of instants which we can get and different methods useful for calculations, creating a new instantly, comparing instants, getting seconds and nanoseconds differently, etc. Instant class is immutable and provides thread safety as compared to the old Date object. The Instant class is much more powerful than the old time-date API.
The above is the detailed content of Java Instant. For more information, please follow other related articles on the PHP Chinese website!

Start Spring using IntelliJIDEAUltimate version...

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

Java...

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Atom editor mac version download
The most popular open source editor

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1
Powerful PHP integrated development environment