How to get current date and time in format YYYY-MM-DD HH:MM:SS.milliseconds in Java?
Hello everyone! I'm a beginner in Java and writing a small application for event logging. I need to write the current time with millisecond precision to a file in the format: `2023-11-15 14:30:25.123`. I tried using `java.util.Date` and `SimpleDateFormat`, but something is going wrong.
Here's my code:
```java
import java.util.Date;
import java.text.SimpleDateFormat;
public class Main {
public static void main(String[] args) {
Date now = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-DD HH:MI:SS.mmm");
String formattedDate = sdf.format(now);
System.out.println(formattedDate);
}
}
```
The output I get is something strange: `2023-11-335 14:09:25.025`. Where does `335` come from instead of the day of the month? And why are minutes displayed as `MI`?
No answers yet.
Log in to leave an answer