Do you want to convert milliseconds to Date in Java ? Actually java.util.Date is internally specified in milliseconds from epoch. So any date is number of millisecond passed since January 1, 1970, 00:00:00 GMT and Date provides constructor which can be used to create Date from milliseconds. Knowing the fact that Date is internally maintained in milliseconds allows you to store date in form of millisecond in Server or in your Class because that can be effectively expressed with a long value. In fact many experienced Java programmer store Date as long value while writing Immutable class which requires Date, one of the reason for that is Date being mutable and long value of Date can be very handy. By the ways this is next in Date related article, we have already discussed How to convert String to Date and How to get current month, year and day of week from Date in Java. If you haven’t read them already, you may find them useful. In this Java tutorial we will see example of converting millisecond into Date in Java.
Java program to convert millisecond to Date in Java
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.
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.
Other Date and Time tutorials from Javarevisited Blog