Practical Java Examples
Real-World Epoch Time Applications
public class PerformanceLogger {
public static void logExecutionTime(Runnable task) {
long startTime = System.currentTimeMillis();
task.run();
long endTime = System.currentTimeMillis();
long executionTime = endTime - startTime;
System.out.printf("Task executed in %d milliseconds%n", executionTime);
}
public static void main(String[] args) {
logExecutionTime(() -> {
// Simulate a time-consuming task
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
}
2. Calculating Date Differences
public class DateDifferenceCalculator {
public static void main(String[] args) {
Instant start = Instant.now();
// Simulate some processing
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Instant end = Instant.now();
Duration timeElapsed = Duration.between(start, end);
System.out.println("Time taken: " +
timeElapsed.toMillis() + " milliseconds");
}
}
Epoch Time Use Cases
graph TD
A[Epoch Time Applications]
A --> B[Caching Mechanisms]
A --> C[Session Management]
A --> D[Database Timestamps]
A --> E[Network Synchronization]
Practical Conversion Scenarios
Time Zone Conversion Example
public class TimeZoneConverter {
public static void convertTimeZones(long epochTime) {
// Convert epoch time to different time zones
ZoneId[] zones = {
ZoneId.of("UTC"),
ZoneId.of("America/New_York"),
ZoneId.of("Asia/Tokyo")
};
for (ZoneId zone : zones) {
ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(
Instant.ofEpochMilli(epochTime),
zone
);
System.out.printf("Time in %s: %s%n", zone, zonedDateTime);
}
}
public static void main(String[] args) {
long currentEpochTime = System.currentTimeMillis();
convertTimeZones(currentEpochTime);
}
}
Common Epoch Time Patterns
Pattern |
Description |
Use Case |
Timestamp Generation |
Create unique identifiers |
Database records |
Time Tracking |
Measure execution time |
Performance monitoring |
Expiration Calculation |
Set time-based limits |
Caching, sessions |
Advanced Epoch Manipulation
public class EpochManipulation {
public static void main(String[] args) {
// Current epoch time
Instant now = Instant.now();
// Add specific duration
Instant futureTime = now.plus(Duration.ofDays(30));
// Check if a time is before or after
boolean isFuture = futureTime.isAfter(now);
System.out.println("Current Time: " + now);
System.out.println("Future Time: " + futureTime);
System.out.println("Is Future: " + isFuture);
}
}
LabEx recommends practicing these examples to master epoch time manipulation in Java, enhancing your time-related programming skills.