✅ Use LocalTime.now()
or LocalDateTime.now()
🔹 Example with LocalTime
:
import java.time.LocalTime;
public class TimeWithMillis {
public static void main(String[] args) {
LocalTime time = LocalTime.now();
System.out.println("Current time: " + time);
}
}
🔹 Output:
Current time: 14:45:12.123
✅ More Common: Use LocalDateTime
(includes date too)
import java.time.LocalDateTime;
public class TimeWithMillis {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
System.out.println("Current datetime: " + now);
}
}
🧠 Want to Extract Just the Milliseconds?
int millis = LocalTime.now().getNano() / 1_000_000;
System.out.println("Milliseconds: " + millis);
⚠️ getNano()
returns nanoseconds — we divide by 1,000,000 to get milliseconds.
🔸 Optional: Format It Nicely
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
LocalTime time = LocalTime.now();
String formatted = time.format(DateTimeFormatter.ofPattern("HH:mm:ss.SSS"));
System.out.println("Formatted: " + formatted);
✅ Output:
Formatted: 14:45:12.123