What is System.currentTimeMillis()?
The System.currentTimeMillis() method returns the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC. The return type is long. This method is often overlooked in favor of new Date(), but they serve different purposes.
Performance Comparison
Many developers default to new Date() when they need the current timestamp. However, new Date() internally calls System.currentTimeMillis(). If you only need the raw millisecond value, calling System.currentTimeMillis() directly is more efficient. When multiple new Date() instances are created within the same method, performance degradation accumulates—storing a single reference is preferable.
Converting Milliseconds to Time Components
The following example demonstrates converting milliseconds since the epoch into hours, minutes, and seconds:
long milliseconds = System.currentTimeMillis();
long seconds = milliseconds / 1000;
long currentSeconds = seconds % 60;
long totalMinutes = seconds / 60;
long currentMinutes = totalMinutes % 60;
long totalHours = totalMinutes / 60;
long currentHours = totalHours % 24;
System.out.println("Milliseconds since epoch: " + milliseconds);
System.out.println(currentHours + ":" + currentMinutes + ":" + currentSeconds + " UTC");
Common Use Cases
Measuring Elapsed Time
This technique is useful for benchmarking code execution duration:
long startTime = System.currentTimeMillis();
for (int i = 0; i < 5; i++) {
Thread.sleep(10);
}
long endTime = System.currentTimeMillis();
System.out.println("Loop duration: " + (endTime - startTime) + " ms");
Formatting Current Date
Combine the timestamp with date formatting utilities:
Date timestamp = new Date(System.currentTimeMillis());
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = formatter.format(timestamp);
System.out.println(formattedDate);
Generating Unique File Names
Using timestamps ensures file name uniqueness:
String uniqueName = "c:\\" + System.currentTimeMillis() + ".tmp";
File file = new File(uniqueName);
file.createNewFile();
Seeding Random Number Generators
Timestamps provide deterministic yet varied seed values:
Random generator = new Random(System.currentTimeMillis());
int randomValue = generator.nextInt(100);
Summary of Time Unit Conversions
| Unit | Milliseconds | Calculation |
|---|---|---|
| 1 second | 1000 | milliseconds / 1000 |
| 1 minute | 60000 | seconds / 60 |
| 1 hour | 3600000 | minutes / 60 |
| 1 day | 86400000 | hours / 24 |
Understanding System.currentTimeMillis() is fundamental for timestamp operations, performance measurement, and generating unique identifiers in Java applications.