$show=/label

Java Instant Examples

SHARE:

A quick guide to Instant class in java 8 api and it is used to represent the time line. Different examples programs on Instant class.

1. Overview

In this tutorial, you'll learn what is instance class in java and how to create an object for Instant class.

This class models a single instantaneous point on the time-line. This might be used to record event time-stamps in the application.

Instant class holds the date time value with nano seconds so it requires the storage of a number larger than a long. To achieve this, the class stores a long representing epoch-seconds and an int representing nanosecond-of-second, which will always be between 0 and 999,999,999.
 
The epoch seconds are measured from the standard Java epoch of 1970-01-01T00:00:00Z value where instants after the epoch have positive values, and earlier instants have negative values.

This class has three constants fields such as EPOCH, MIN, MAX.

Java Instant Examples


2. Instant Class Methods


public static Instant now(): it is used to get the current date and time in Instance object. This value is optained from system clock.

Temporal adjustInto(Temporal temporal): It is used to adjust the specified temporal object to have this instant.
int get(TemporalField field): It is used to get the value of the specified field from this instant as an int.

boolean isSupported(TemporalField field): It is used to check if the specified field is supported.

Instant minus(TemporalAmount amountToSubtract): It is used to return a copy of this instant with the 
specified amount subtracted.

static Instant parse(CharSequence text): It is used to obtain an instance of Instant from a text string such as 2007-12-03T10:15:30.00Z.

Instant plus(TemporalAmount amountToAdd): It is used to return a copy of this instant with the specified amount added.

Instant with(TemporalAdjuster adjuster): It is used to return an adjusted copy of this instant.


3. Java Instant Examples

3.1 Instant Object Creation


Use now() method to get the object for Instant class from current system time.
package com.javaprogramto.java8.dates.instant;

import java.time.Instant;

public class InstantCreationExample {

	public static void main(String[] args) {

		// Creating instant object from now()
		Instant instant1 = Instant.now();
		System.out.println("Instant 1 value from now() - " + instant1);

		Instant instant2 = Instant.now();
		System.out.println("Instant 2 value from now() - " + instant2);
	}
}
 
Output:
Instant 1 value from now() - 2020-11-29T13:35:31.836392Z
Instant 2 value from now() - 2020-11-29T13:35:31.849851Z
 

3.2 Creating Instant From String - parse()


We can convert a String value to Instant object using Instant.parse() method. This parse() method takes string argument.
package com.javaprogramto.java8.dates.instant;

import java.time.Instant;

public class InstantParseExample {
	public static void main(String[] args) {

		// Creating instant object from parse()
		Instant instantFromStr1 = Instant.parse("2020-11-29T13:35:30.01Z");
		System.out.println("Instant 1 from string using parse() : " + instantFromStr1);

		Instant instantFromStr2 = Instant.parse("2020-12-29T13:35:31.00Z");
		System.out.println("Instant 2 from string using parse() : " + instantFromStr2);
	}
}
 
Output:
Instant 1 from string using parse() : 2020-11-29T13:35:30.010Z
Instant 2 from string using parse() : 2020-12-29T13:35:31Z
 

3.3 Create Instant from Epoch Second Value


Use ofEpochMilli() method to convert long epoch second value to Instant object.
package com.javaprogramto.java8.dates.instant;

import java.time.Instant;

public class InstantEpochSecondExample {
	public static void main(String[] args) {

		// Creating instant object from ofEpochMilli()
		Instant instantFromEpochSecond1 = Instant.ofEpochMilli(1606657474l);
		System.out.println("Instant 1 from Epoch Second value using  ofEpochMilli() : " + instantFromEpochSecond1);

		Instant instantFromEpochSecond2 = Instant.ofEpochMilli(1667137474l);
		System.out.println("Instant 2 from Epoch Second value using  ofEpochMilli() : " + instantFromEpochSecond2);
	}
}
 
Output:
Instant 1 from Epoch Second value using  ofEpochMilli() : 1970-01-19T14:17:37.474Z
Instant 2 from Epoch Second value using  ofEpochMilli() : 1970-01-20T07:05:37.474Z
 

3.4 Convert Instant to Long value


Use getEpochSecond() method to get the epoch second value from the existing instant object.
package com.javaprogramto.java8.dates.instant;

import java.time.Instant;

public class InstantGetEpochExample {
	public static void main(String[] args) {

		// Creating instant object from now()
		Instant instant1 = Instant.now();
		
		// Getting long value in epoch style from instant object
		long epoch1 = instant1.getEpochSecond();
		System.out.println("Instant 1 "+instant1);
		System.out.println("epoch 1 "+epoch1);

		// Another example to get the epoch value
		Instant instant2 = Instant.now();
		long epoch2 = instant2.getEpochSecond();
		System.out.println("Instant 2 "+instant2);
		System.out.println("epoch 2 "+epoch2);
	}
}
 
Output:
Instant 1 2020-11-29T13:56:40.849772Z
epoch 1 1606658200
Instant 2 2020-11-29T13:56:40.862042Z
epoch 2 1606658200
 

3.5 Adding n Time Units to Instant


Use plus() method to add a specific amount of time unit to the existing instant object.

package com.javaprogramto.java8.dates.instant;

import java.time.Instant;
import java.time.temporal.ChronoUnit;

public class InstantPlusExample {
	public static void main(String[] args) {

		// Creating instant object from string using parse()
		Instant instant1 = Instant.parse("2020-11-29T13:56:40.11Z");

		// Adding 60 seconds
		Instant addedSeconds = instant1.plus(60l, ChronoUnit.SECONDS);
		System.out.println("Added 60 seconds : " + addedSeconds);

		// Another example to add 60 minutes
		Instant instant2 = Instant.parse("2020-11-29T13:56:40.11Z");

		// Adding 60 minutes
		Instant addedMinutes = instant2.plus(60l, ChronoUnit.MINUTES);
		System.out.println("Added 60 Minutues : " + addedMinutes);
	}
}
 
Output:
Added 60 seconds : 2020-11-29T13:57:40.110Z
Added 60 Minutues : 2020-11-29T14:56:40.110Z
 

3.6 Subtracting n Time Units from Instant


Use minus() method to subtract n number of a specific time units.
package com.javaprogramto.java8.dates.instant;

import java.time.Instant;
import java.time.temporal.ChronoUnit;

public class InstantMinusExample {
	public static void main(String[] args) {

		// Creating instant object from string using parse()
		Instant instant1 = Instant.parse("2020-11-29T13:56:40.11Z");

		// Removing 60 seconds
		Instant addedSeconds = instant1.minus(60l, ChronoUnit.SECONDS);
		System.out.println("Minus 60 seconds : " + addedSeconds);

		// Another example to add 60 minutes
		Instant instant2 = Instant.parse("2020-11-29T13:56:40.11Z");

		// Subtracting 60 minutes
		Instant addedMinutes = instant2.minus(60l, ChronoUnit.MINUTES);
		System.out.println("Minus 60 Minutues : " + addedMinutes);
	}
}
 
Output:
Minus 60 seconds : 2020-11-29T13:55:40.110Z
Minus 60 Minutues : 2020-11-29T12:56:40.110Z
 

3.7 Comparing Instant Objects


Use equals() method to compare two Instance objects. And also we can use isAfter() and isBefore() methods to check if the instance 1 is before or after another Instance 2.
package com.javaprogramto.java8.dates.instant;

import java.time.Instant;
import java.time.temporal.ChronoUnit;

public class ComoareInstancesExample {
	public static void main(String[] args) {

		// Creating instant object 1
		Instant instant1 = Instant.parse("2020-11-29T13:56:40.11Z");

		// Creating instant object 2
		Instant instant2 = Instant.parse("2022-11-30T13:56:40.11Z");

		// comparing two instants using equals() method
		boolean isEquals = instant1.equals(instant2);
		
		if(isEquals) {
			System.out.println("instant1 & instant2 are same");
		} else {
			System.out.println("instant1 & instant2 are not same");
		}
		
		// comparing Instants using isAfter()
		boolean isAfter = instant1.isAfter(instant2);
		
		if(isAfter) {
			System.out.println("instant1 is after instant2");
		} else {
			System.out.println("instant1 is not after instant2");
		}
		
		// comparing Instants using isBefore()
		boolean isBefore = instant1.isBefore(instant2);
		
		if(isBefore) {
			System.out.println("instant1 is before instant2");
		} else {
			System.out.println("instant1 is not before instant2");
		}
	}
}
 
Output:
instant1 & instant2 are not same
instant1 is not after instant2
instant1 is before instant2
 

4. Conclusion


In this article, You've seen how to use Instant class to work with the precise time lines and what are the methods needed to work with Instance objects.




COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,16,Arrays,16,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,5,Collections,25,Collector,1,Command Line,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,90,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,35,Dictionary,1,Difference,1,Download,1,Eclipse,2,Efficiently,1,Error,1,Errors,1,Exception,1,Exceptions,3,Fast,1,Files,10,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,4,Grant,1,Grep,1,HashMap,1,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,5,Iterate,2,Jackson API,3,Java,30,Java 10,1,Java 11,5,Java 12,5,Java 13,2,Java 14,2,Java 8,100,Java 8 Difference,2,Java 8 Stream Conversions,2,java 8 Stream Examples,3,Java 9,1,Java Conversions,11,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,103,java.lang,5,java.util. function,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,1,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,2,Math,1,Matrix,5,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,27,String,58,String Programs,12,String Revese,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,16,Unix,3,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: Java Instant Examples
Java Instant Examples
A quick guide to Instant class in java 8 api and it is used to represent the time line. Different examples programs on Instant class.
https://1.bp.blogspot.com/-TSUJ-JfAG6A/X8Oz6kTSERI/AAAAAAAADFw/yu8CDNjxHb07hcXdUKgIahWGqxc3kXragCLcBGAsYHQ/w640-h466/Java%2BInstant%2BExamples.png
https://1.bp.blogspot.com/-TSUJ-JfAG6A/X8Oz6kTSERI/AAAAAAAADFw/yu8CDNjxHb07hcXdUKgIahWGqxc3kXragCLcBGAsYHQ/s72-w640-c-h466/Java%2BInstant%2BExamples.png
JavaProgramTo.com
https://www.javaprogramto.com/2020/11/java-instant.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2020/11/java-instant.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content