Converting Milliseconds to Date in Java

Many Web Service specifications represent dates as number of milliseconds elapsed since 1st January 1970. This representation also enables us to store and transfer date values as long values. However when want to manipulate dates such as adding days or months, this long value is cumbersome to process. In such cases we want to work with java.util.Date.

The following program shows how we can easily convert number of milliseconds after 1970 to a Java Date,


import java.util.Date;

/**

 * Convert number of milliseconds elapsed since 1st January 1970 to a java.util.Date 

 */

public class MilliSecsToDate {
    public static void main(String[] args) {
        MilliSecsToDate md = new MilliSecsToDate();
        // The long value returned represents number of milliseconds elapsed
        // since 1st January 1970.
        long millis = System.currentTimeMillis();
        Date currentDate = new Date(millis);
        System.out.println("Current Date is "+currentDate);
    }
}

If you need to get the number of milliseconds elapsed since 1st January 1970, you can use the method getTime() on java.util.Date. This is useful when you want to store or transfer date values.

Do you have a programming problem that you are unable to solve? Please send us your problem and we will publish the solution on this site within 48 hours! Please email us.


Leave a Reply