×

Convert milliseconds to date in Java

In Java, we frequently need to convert milliseconds into Dates with several formats, including dd MM yyyy and dd MM yyyy HH:mm:ss:SSS Z, among others.

The Date class is one of the most crucial Java classes for working with dates. The Date is internally stored in milliseconds. We can construct a Date from milliseconds by utilizing the constructor of the Date class.

It is necessary to familiarise yourself with the SimpleDateFormat class before moving on. One of the classes we use to format and parse data is this one. It aids in the conversion of dates between different formats. It helps convert a string-formatted date into a date object. In simple terms, Date is modified appropriately by using the SimpleDateFormat class.

Java has numerous options for converting milliseconds to dates. Both the java.util.Calendar.setTimeInMillis() method and the java.util.Date(long Millis) method is available. Examples of both approaches to constructing Date from A Millisecond in Java will be shown in this article.

In this case, we are formatting Date in Java using SimpleDateFormat, which is not thread-safe and shouldn't be shared by several threads.

Program 1

Filename: MillisecondsToDate1.java

import java.text.DateFormat;   
import java.text.SimpleDateFormat;   
import java.util.Date;   
import java.util.Scanner;   
// to translate milliseconds into dates, develop the MillisecondsToDate1 class.
public class MillisecondsToDate1 {   
// start the main() method
public static void main(String args[])   
{   
    // declaration for the milliseconds variable
        long miliSec;   
        // Scanner class object creation
    Scanner sc = new Scanner(System.in);     
                System.out.print("Enter milliseconds: ");     
                // receive user input and initialize the variable
             miliSec = sc.nextLong();     
                // close scanner class obj   
             sc.close();   
             // to change the date object, create a new instance of the SimpleDateFormat class. 
             DateFormat obj = new SimpleDateFormat("dd MMM yyyy HH:mm:ss:SSS Z");   
                //We create a Date instance and supply the constructor with milliseconds.
                Date res = new Date(miliSec);   
                // The res is now formatted using SimpleDateFormat.                
             System.out.println(obj.format(res));   
}   
}   

Output

Convert milliseconds to date in Java

Program 2

Filename: MillisecondsToDate2.java

import java.text.DateFormat;   
import java.text.SimpleDateFormat;   
import java.util.Calendar;   
import java.util.Date;   
// to transform milliseconds into dates, develop the MillisecondsToDate2 class.
public class MillisecondsToDate2 {   
// start the main() method
    public static void main(String args[]) {   
       // To obtain the current time in milliseconds, use the system's currentTimeMillis() method.
       long milliSec = System.currentTimeMillis();   
       // By creating an object of the date class and providing milliseconds to the constructor, you can convert milliseconds into the Date.
       Date res = new Date(milliSec) ;   
       // printing the Date value (default format)
       System.out.println("After converting milliseconds into date: " + res);   
       // Make an instance of the SimpleDateFormat class to convert the date object to dd: MMM yyyy HH:mm:ss:SSS Z and dd:MM:yy:HH:mm:ss format.
       DateFormat sdf1 = new SimpleDateFormat("dd:MM:yy:HH:mm:ss") ;   
       DateFormat sdf2 = new SimpleDateFormat("dd MMM yyyy HH:mm:ss:SSS Z") ;   
       // after converting the res into dd:MM:yy:HH:mm:ss and dd MMM yyyy HH:mm:ss:SSS Z format
       System.out.println("Date in dd:MM:yy:HH:mm:ss: " + sdf1.format(res));   
       System.out.println("Date in dd MMM yyyy HH:mm:ss:SSS Z: " + sdf2.format(res));   
       // Using the calendar class, convert milliseconds to dates.
       // a Calendar class instance should be created.
       Calendar calndr = Calendar.getInstance();   
       // To set the time, use the calendar class's setTimeInMillis() method.          calndr.setTimeInMillis(milliSec);   
       // after formatting the date into dd:MM:yy:HH:mm:ss   
       System.out.println("After converting milliseconds into date using Calendar class: "+ sdf1.format(calndr.getTime()));   
       // transferring data from one date to another
       Date currentdate = new Date();   
       Date tempDate = new Date(currentdate.getTime());   
       System.out.println("original Date: " + sdf1.format(currentdate));   
       System.out.println("copied Date: " + sdf1.format(tempDate));   
    }   
}   

Output

Convert milliseconds to date in Java

Program 3

Filename: MillisToDate.java

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;


public class MillisToDate {
 
    public static void main(String args[]) {
     
       // java.util.Date is used to convert milliseconds to dates.
       //current time in milliseconds
       long currentDateTime = System.currentTimeMillis();
     
       // making a date from milliseconds
       Date currentDate = new Date(currentDateTime) ;
     
       //printing value of Date
       System.out.println("current Date: " + currentDate) ;
     
       DateFormat df = new SimpleDateFormat("dd:MM:yy:HH:mm:ss") ;
     
       //formatted value of current Date
       System.out.println("Milliseconds to Date: " + df.format(currentDate))  ;
     
       //Converting milliseconds to Date using Calendar
       Calendar cal = Calendar.getInstance();
       cal.setTimeInMillis(currentDateTime) ;
       System.out.println("Milliseconds to Date using Calendar:"
               + df.format(cal.getTime())) ;
     
       //copying one Date's value into another Date in Java
       Date now = new Date() ;
       Date copiedDate = new Date(now.getTime()) ;
     
       System.out.println("original Date: " + df.format(now)) ;
       System.out.println("copied Date: " + df.format(copiedDate)) ;
    }
     
}

Output

Convert milliseconds to date in Java

That concludes the discussion about milliseconds and dates in Java. Two methods have been demonstrated, one of which uses the Date class and the other of the Calendar class.


Related Topics

Minimum Number of Platforms Required for a Railway Station

The train station problem is one of the most significant problems typically posed in the programming round interview to gauge a candidate's aptitude for logic and problem-solving. Problem of Railway Station The...

6 minutes read.

Java 16

Java 16 is the most recent short-term incremental release, based on Java 15, and it was released on March 16, 2021. Records and sealed classes are just two of the...

11 minutes read.

How to Return Value from Lambda Expression Java?

What is Lambda Expression in Java? In Java 8, Lambda Expressions were introduced.A lambda expression is a brief section of code that accepts input and outputs a value. Similar to methods,...

4 minutes read.

Stack Program in Java

Stack Program in Java The Stack class is part of the collection framework that inherits the Vector class. Thus, the Stack class can also be called a subclass of the Vector...

5 minutes read.

Java Print Writer

PrintWriter: It is used to write output data from the file. It is the class of Java.io package. It inherits the properties of the Writer class. Writer Class: It is a class of...

4 minutes read.

Java Byte Keyword

Byte: The Keyword Byte in Java programming language is a primitive data type.Digital content that is most used for eight bits is called as a byte.The Java Byte Keyword is used...

3 minutes read.

Java extend multiple classes

In Java, what does extend mean? One of several Java inheritance keywords is extended, meaning we pass all or most of the Parent class's characteristics through to the Child class. The...

3 minutes read.

How to Iterate List in Java?

List is a Collection foundation interface in Java. It enables us to keep the collection of objects in order. The four classes that make up the List interface implementation are...

3 minutes read.

Minimum Difference Between Groups of Size Two in Java

There is given an array with various integers in it. The goal is to divide the elements into distinct groups, each of which has just two, so that the difference...

3 minutes read.

Heart Pattern in Java

Heart Pattern is yet another intricate pattern program, however, due to its complexity, interviewers hardly ever inquire about it. Method for Printing the Heart Number Pattern Put the value of the total row...

2 minutes read.

Streams in Java

The conventional Java SE 8 version came with many new peculiarities, out of which the most striking of which are assuredly lambda expressions and the method references. Streams and Streams...

14 minutes read.

Java Externalization

What is Externalization in Java? Externalization is a concept that is advanced to serialization. Serialization is a concept where we can transfer an object from our JVM ( Java virtual machine...

3 minutes read.

How Many Ways to Create Objects in Java

Introduction Java comes under the category of object-oriented programming languages. Since it is object-oriented, everything in Java is considered an object. Java is a diverse programming language that is designed to...

6 minutes read.

Java.net.SocketException

Exception The problem occurred during the execution of the program. If an exception occurs in the program, the program gets terminated. To skip the exception occurring statements, we have to handle...

4 minutes read.

Getting the Day from the Date in Java?

To extract the day's name from the date, we will write Java application. When dealing the date and time in Java, the following classes are used. Class for Calendars: This class is...

6 minutes read.

Java Project Ideas

When it comes to constructing projects, Java is regarded as one of the best languages and is also one of the most paid. Java excels in any application, whether it...

10 minutes read.

Getting Synchronized Set from Java HashSet

The synchronizedSet() technique for java.util.Collections class is utilized to return a synchronized (string safe) set supported by the predetermined set. To ensure sequential access, it is important that everything admittance...

4 minutes read.

Java exception list

Java uses exceptions, like the majority of contemporary programming languages, to deal with both errors and "extraordinary events." When an exception arises inside the program, it messes up the regular...

6 minutes read.

Java Polymorphism

The process of representing one form in multiple forms is known as Polymorphism. Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means many and "morphs" means forms. So polymorphism means...

5 minutes read.

How to Set Environment Variables for Java

Introduction Java is an object-oriented programming language that is based on classes and can be employed mostly to develop web and desktop applications. No matter the computer architecture, Java applications are...

7 minutes read.