Practical Timestamp Examples
Real-World Timestamp Applications
public class PerformanceTracker {
public static void measureExecutionTime() {
long startTime = System.currentTimeMillis();
// Code block to measure
for (int i = 0; i < 1000000; i++) {
Math.sqrt(i);
}
long endTime = System.currentTimeMillis();
long executionTime = endTime - startTime;
System.out.println("Execution Time: " + executionTime + " ms");
}
public static void main(String[] args) {
measureExecutionTime();
}
}
2. Logging and Event Tracking
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
public class EventLogger {
private static final DateTimeFormatter formatter =
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
.withZone(ZoneId.systemDefault());
public static void logEvent(String eventName) {
Instant timestamp = Instant.now();
String formattedTimestamp = formatter.format(timestamp);
System.out.println("[" + formattedTimestamp + "] Event: " + eventName);
}
public static void main(String[] args) {
logEvent("User Login");
logEvent("Data Processing Started");
logEvent("Data Processing Completed");
}
}
Timestamp Use Case Scenarios
graph TD
A[Timestamp Applications] --> B[Performance Monitoring]
A --> C[Event Logging]
A --> D[Data Synchronization]
A --> E[Caching Mechanisms]
3. Expiration and Timeout Handling
import java.time.Instant;
import java.time.Duration;
public class TokenValidator {
private Instant creationTime;
private static final Duration TOKEN_VALIDITY = Duration.ofHours(1);
public TokenValidator() {
this.creationTime = Instant.now();
}
public boolean isTokenValid() {
Instant now = Instant.now();
Duration elapsed = Duration.between(creationTime, now);
return elapsed.compareTo(TOKEN_VALIDITY) < 0;
}
public static void main(String[] args) throws InterruptedException {
TokenValidator token = new TokenValidator();
// Simulate token usage
Thread.sleep(2000); // Wait 2 seconds
System.out.println("Token Valid: " + token.isTokenValid());
}
}
Timestamp Comparison Methods
Operation |
Method |
Description |
Compare Timestamps |
compareTo() |
Check temporal order |
Calculate Duration |
Duration.between() |
Compute time difference |
Check Expiration |
isAfter() , isBefore() |
Temporal validation |
4. Database Timestamp Management
import java.sql.Timestamp;
import java.time.Instant;
public class DatabaseTimestampDemo {
public static Timestamp getCurrentTimestamp() {
return Timestamp.from(Instant.now());
}
public static void main(String[] args) {
Timestamp currentTimestamp = getCurrentTimestamp();
System.out.println("Current Database Timestamp: " + currentTimestamp);
}
}
Best Practices
- Use
Instant
for precise timestamp operations
- Consider timezone implications
- Implement proper timestamp validation
- Use appropriate formatting for different contexts
With LabEx's comprehensive Java programming resources, developers can effectively manage timestamps in various application scenarios.