Sunday, November 17, 2024
Google search engine
HomeLanguagesJavaProgram to Convert Milliseconds to a Date Format in Java

Program to Convert Milliseconds to a Date Format in Java

Given milliseconds. The task is to write a program in Java to convert Milliseconds to a Date that Displays the date in dd MMM yyyy HH:mm:ss:SSS Z format.
The Date class in Java internally stores Date in milliseconds. So any date is the number of milliseconds passed since January 1, 1970, 00:00:00 GMT and the Date class provides a constructor which can be used to create a Date from milliseconds.
The SimpleDateFormat class helps in the formatting and parsing of data. We can change the date from one format to other. It allows the user to interpret string date format into a Date object. We can modify date accordingly.

Constructors of SimpleDateFormat: 

  • SimpleDateFormat(String pattern_arg) : Constructs a Simple Date Format using the given pattern – pattern_arg, default date format symbols for the default FORMAT locale.
  • SimpleDateFormat(String pattern_arg, Locale locale_arg) : Constructs a Simple Date Format using the given pattern – pattern_arg, default date format symbols for the given FORMAT Locale – locale_arg.
  • SimpleDateFormat(String pattern_arg, DateFormatSymbols formatSymbols) : Constructs a SimpleDateFormat using the given pattern – pattern_arg and date format symbols.

Below is the program to convert milliseconds to a Date Format in Java: 

Java




// Java program to convert milliseconds
// to a Date format
 
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
 
public class SectoDate {
    public static void main(String args[])
    {
 
        // milliseconds
        long milliSec = 3010;
 
        // Creating date format
        DateFormat simple = new SimpleDateFormat(
            "dd MMM yyyy HH:mm:ss:SSS Z");
 
        // Creating date from milliseconds
        // using Date() constructor
        Date result = new Date(milliSec);
 
        // Formatting Date according to the
        // given format
        System.out.println(simple.format(result));
    }
}


Output

01 Jan 1970 00:00:03:010 +0000

Time complexity: O(1) because it is performing constant operations
Auxiliary space: O(1)

RELATED ARTICLES

Most Popular

Recent Comments