-1

Into a Java application I have this String representing a timestamp containing values like this: 2009-10-17 05:45:14.000

As you can see the string represents the year, the month, the day, the hour, the minute, the second and the millisencond.

I have to convert a String like this into a Date object (if possible bringing also the millisecond information, is it possible?)

How can I correctly implement it?

AndreaNobili
  • 40,955
  • 107
  • 324
  • 596
  • 4
    Does this answer your question? [Parse CIM\_DateTime with milliseconds to Java Date](https://stackoverflow.com/questions/37308672/parse-cim-datetime-with-milliseconds-to-java-date) - There are probably dozens of similar questions. Check this one. It's not exactly the same, but it does take into consideration date+time (including millis). In that ansewer, find the bit that uses `DateTimeFormatter`. – Augusto Jul 18 '20 at 12:08

2 Answers2

2

You can use SimpleDateFormat to parse a given string date according to a given pattern, it also supports milliseconds, like this:

SimpleDateFormat format= new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");
Date date=format.parse("2009-10-17 05:45:14.050");
Ismail
  • 2,322
  • 1
  • 12
  • 26
1

Since Java 8, you should use the classes in the date-time API
Class LocalDateTime stores a date and a time up to nanosecond precision.
Here is a snippet showing how to parse a string into an instance of LocalDateTime

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class DateTime {
    public static void main(String[] args) {
        String str = "2009-10-17 05:45:14.000";
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS", Locale.ENGLISH);
        LocalDateTime ldt = LocalDateTime.parse(str, formatter);
    }
}
Abra
  • 19,142
  • 7
  • 29
  • 41