×

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

Java Network Programming (Socket Programming in Java)

JAVA NETWORK Network programming is used to execute programs across multiple machines that are connected by a network. The java.net package contains a collection of classes and interfaces that provide this...

3 minutes read.

Big Decimal class in Java

The fairly Big pretty Decimal class provides operations for arithmetic, rounding, comparison and format conversion in a sort of big way. It can handle generally large and very small floating-point...

6 minutes read.

Java Anon Proxy

The Java Anon Proxy (JAP), also known as JonDonym, is a proxy system designed to enable Web browsing with revocable (the use of or publication under a pseudonym, a false...

4 minutes read.

Java Map Example

In Java, the Map is an interface that is used mainly to denote key and value pairs. The central concept and theme of this mapping in the java collection framework...

4 minutes read.

Fork Join in Java

Multithreaded processors are being introduced in new computer systems today. The operation is faster due to multicore CPUs. Therefore, it becomes essential for a programmer to leverage multithreaded processors effectively...

4 minutes read.

Java Append Data to File

When writing data to a file using the classes within the java.io package, its file will often be overwritten, meaning that any existing data will be removed and new data...

4 minutes read.

Constructor in Java with Example

Java Constructor  The constructor is used for object initialization. It's a block of code that initializes a newly created object. It contains a collection of statements that are executed at the...

5 minutes read.

Java 8 Consumer Interface in Java

The Consumer Interface is used to implement the functional programming in Java. The Consumer Interface indicates a function that accepts a single input and outputs a result. These functions don’t...

2 minutes read.

Java Math nextUp() Method

The nextUp() method of Math class returns the floating-point number adjacent to the argument in direction of the positive infinity. Syntax: public static double nextUp (double d)public static float nextUp (float f) Parameters: The...

2 minutes read.

Java Integer lowestOneBit()

The lowestOneBit () method of Java Integer class returns an int value with at most a single one-bit, in the position of the lowest-order one-bit in the specified int value.  Syntax public...

2 minutes read.

Facts about null in Java

Nearly all programming languages have a relationship with null. Hardly any programmers are unconcerned by null. The null has a java.lang.NullPointerException association in Java. Given that it is a class...

4 minutes read.

Prime Number Program in Java

Prime Number Program in Java using for loop A natural number which is greater than 1 and has only two factors the number itself and 1 is called prime number. In...

2 minutes read.

Hierarchy of operators in Java

Operators are the most frequently used terminology in any area of programming, and it helps in various approaches to efficiently solve daily life problems by computer programming. The simple addition of...

4 minutes read.

Java Boolean logicalOr() Method

The logicalOr() method of Java Boolean class returns the result of implementing logical OR operation on the specified Boolean operands. Syntax: public static boolean logicalOr (boolean a, boolean b) Parameters: The parameters ‘a’ and...

2 minutes read.

Java Type Casting

Type casting is a technique or process used in Java to convert one data type into another, either manually or automatically. The compiler performs the automatic conversion, and the programmer...

3 minutes read.

How to check valid date in Java?

Every time we get data for any application, we must first ensure that it is accurate before continuing with any further processing. We might have to confirm the following while dealing...

4 minutes read.

Difference Between Java and PHP

The two most used programming languages are PHP and Java. Both of them have a lot of similarities and distinctions. Let's first grasp each of them individually before examining their...

3 minutes read.

Java this keyword

This Keyword in Java This keyword can be used in many different ways in Java. This is a reference variable in Java that points to the active object. In Java, the...

8 minutes read.

How to Change the Day in the Date using Java?

To operate with the date and time in Java, we need the Calendar abstract class. It provides a number of helpful interfaces that enable us to convert dates between a...

4 minutes read.

Heap Sort in Java

Heap Sort in JavaHeap sort in Java uses the data structure binary heap, min-heap, or max heap to do the sorting of elements. Since min-heap always gives the minimum element first,...

8 minutes read.