java tutorial: java get timestamp milliseconds

Java get timestamp:

// method 1
System.currentTimeMillis(); 

// method 2
Calendar.getInstance().getTimeInMillis(); 

// method 3
new Date().getTime();

Test code:

import java.util.Calendar;
import java.util.Date;

public class TestGetTimestamp {
    public static void main(String[] args) {
        long currentTimeMillis = System.currentTimeMillis();
        System.out.println("currentTimeMillis = " + currentTimeMillis);

        long timeInMillis = Calendar.getInstance().getTimeInMillis();
        System.out.println("currentTimeMillis = " + timeInMillis);

        long time = new Date().getTime();
        System.out.println("currentTimeMillis = " + time);
    }
}

Three ways to perform efficiency testing.

import java.util.Calendar;
import java.util.Date;

public class TestGetTimeEffectiv {
    private static long TEN_THOUSAND=10000;

    public static void main(String[] args) {
        long times = 1000 * TEN_THOUSAND;
        
        long t1=System.currentTimeMillis();
        testSystem(times);
        long t2=System.currentTimeMillis();
        System.out.println("System.currentTimeMillis time = " + (t2-t1));

        testCalander(times);
        long t3=System.currentTimeMillis();
        System.out.println("Calendar.getInstance().getTimeInMillis time = " + (t3-t2));

        testDate(times);
        long t4=System.currentTimeMillis();
        System.out.println("new Date().getTime() time = " + (t4-t3));
    }

    public static void testSystem(long times) {
        for(int i=0;i<times;i++){
            long currentTime = System.currentTimeMillis();
        }
    }

    public static void testCalander(long times) {
        for(int i=0;i<times;i++){
            long currentTime= Calendar.getInstance().getTimeInMillis();
        }
    }

    public static void testDate(long times) {
        for(int i=0;i<times;i++){
            long currentTime=new Date().getTime();
        }
    }
}

Calendar.getInstance().getTimeInMillis() is the slowest, because Canlendar takes more time to deal with time zone issues.

Add a Comment

Your email address will not be published.