Java System.currentTimeMillis() – Examples
In this tutorial, we will learn about the Java System.currentTimeMillis() function, and learn how to use this function to get the current time in milliseconds, with the help of examples.
currentTimeMillis()
System.currentTimeMillis() returns the current time in milliseconds. It is the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC.
Syntax
The syntax of currentTimeMillis() function is
currentTimeMillis()
Returns
The function returns static long value.
Example 1 – currentTimeMillis()
In this example, we will make a call to System.currentTimeMillis() and get the current time in milli-seconds.
Java Program
public class Example {
public static void main(String args[]) {
long millis = System.currentTimeMillis();
System.out.println(millis);
}
}
Output
1607577603208
Example 2 – currentTimeMillis() – Time for Code Run
We can use System.currentTimeMillis() to calculate the time taken to run a block of code in milli-seconds. Get the current time before and after running the code block, and the difference of these values should give you the time taken to run the block of code in milli-seconds.
For the code block, we will take a for loop that iterates One Billion times.
Java Program
public class Example {
public static void main(String args[]) {
long millis1 = System.currentTimeMillis();
System.out.println("Before code run : " + millis1);
for(long i = 0; i < 1000000000L;i++) {
}
long millis2 = System.currentTimeMillis();
System.out.println("After code run : " + millis2);
long diff = millis2 - millis1;
System.out.println("Time taken by for loop : " + diff + " milli-seconds");
}
}
Output
Before code run : 1607578028702
After code run : 1607578029000
Time taken by for loop : 298 milli-seconds
It took around quarter of a second.
Conclusion
In this Java Tutorial, we have learnt the syntax of Java System.currentTimeMillis() function, and also learnt how to use this function with the help of examples.