Java Instant
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!

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.
