
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Convert Java Util Date to Instant
In this article, we will learn to convert a date object to an Instant object in Java. The Instant class represents a specific moment on the timeline, often used for precise time calculations. We'll use the toInstant() method provided by the Date class to achieve this conversion
Problem Statement
Write a program in Java to convert date to instant.
Input
>Date = Thu Apr 18 23:32:07 IST 2019
Output
java.util.Date to Instant = 2019-04-18T18:02:07.330Z
Steps to convert java.util.Date to Instant
Following are the steps to convert date to instant ?
- Start by importing the Instant class from java.time.
- Initialize the demo class.
- In the main method, we will initialize the Instant object and use the toInstant() method to convert the date into instant.
- At last, we will print the instant.
Java program to convert java.util.Date to Instant
Below is the Java program to convert date to instant ?
import java.time.Instant; public class Demo { public static void main(String[] args) { java.util.Date date = new java.util.Date(); System.out.println("Date = "+date); Instant instant = date.toInstant(); System.out.println("java.util.Date to Instant = "+instant); } }
Output
Date = Thu Apr 18 23:32:07 IST 2019 java.util.Date to Instant = 2019-04-18T18:02:07.330Z
Code Explanation
We begin by importing the necessary classes, including java.time.Instant for handling time instances. Inside the main method, we create a Date object representing the current date and time. We then convert this Date object to an Instant using the toInstant() method. Finally, the program prints both the original Date and the converted Instant to the console, showing the transformation from a date to a precise timestamp.