Table of Contents
Syntax
Methods of Java Instant
Examples to Implement Java Instant
1. toString()
2. getEpochSecond()
3. getNano()
4. plusSeconds()
5. compareTo()
Conclusion
Home Java javaTutorial Java Instant

Java Instant

Aug 30, 2024 pm 03:49 PM
java

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();
Copy after login

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;
Copy after login

This static field will return an Instance of Instant class representing the exact EPOCH time.

Instant instant = Instant.MAX;
Copy after login

This static field will return an Instance of Instant class representing the maximum value of the instance.

Instant instant = Instant.MIN;
Copy after login

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.
Note: Please note that the Instant class is an immutable class, so it will return a new instance for every manipulative operation.
  • 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() );
}
}
Copy after login

Output:

Java Instant

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() );
}
}
Copy after login

Output:

Java Instant

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() );
}
}
Copy after login

Output:

Java Instant

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 );
}
}
Copy after login

Output:

Java Instant

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 ) );
}
}
Copy after login

Output:

Java Instant

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

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

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

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

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

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

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

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

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

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

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

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.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

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 vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

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.

See all articles