There are many different ways to convert milliseconds into Date in Java. One can use java.util.Date(long Millis) constructor or java.util.Calendar.setTimeInMillis() method. In this article we will see example of both methods to create Date from Millisecond in Java. By the way here we are using SimpleDateFormat to format Date in Java which is not thread-safe and should not be shared between multiple threads.


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

/**
 * Java program to convert  Millisecond to Date in JavaJava API provides utility
 * method to get millisecond from Date and convert Millisecond to Date in Java.
 *
 */

public class MillisToDate {

    public static void main(String args[]) {
   
       //Converting milliseconds to Date using java.util.Date
       //current time in milliseconds
       long currentDateTime = System.currentTimeMillis();
   
       //creating Date from millisecond
       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:
current Date: Wed Feb 29 01:58:46 VET 2012
Milliseconds to Date29:02:12:01:58:46
Milliseconds to Date using Calendar:29:02:12:01:58:46
original Date29:02:12:01:58:46
copied Date29:02:12:01:58:46

 

Another useful usage of keeping Date in millisecond is, It’s easy to convert between java.util.Date and java.sql.Date. As SQL doesn't provide Date in form of java.util.Date you often need to convert SQL Date to util Date but keep value of Date as long millisecond value allows you to create both java.sql.Date and java.util.Date. One more benefit of keeping date in long millisecond value is, it’s easy to copy value of one Date into another in Java.

That's all on how to convert milliseconds to Date in Java. We have seen two approach one is using Date class while other is using Calendar class. I personally prefer java.util.Date way. let me know if you come across any other way of converting milliseconds into Date in Java.

0 comments :

Post a Comment

 
Top