Calendar and Date class instance methods are used to convert millis to Date.
This example shows how to convert Milliseconds to Date in Java.
Converting Milliseconds to Date in Java – Millis to Date Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
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[]) { //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 Date: 29:02:12:01:58:46
Milliseconds to Date using Calendar:29:02:12:01:58:46
original Date: 29:02:12:01:58:46
copied Date: 29:02:12:01:58:46
Milliseconds to Date: 29:02:12:01:58:46
Milliseconds to Date using Calendar:29:02:12:01:58:46
original Date: 29:02:12:01:58:46
copied Date: 29:02:12:01:58:46