java.time
The java.util
Date-Time API and their formatting API, SimpleDateFormat
are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*, released in March 2014 as part of Java SE 8 standard library.
Solution using java.time
, the modern Date-Time API:
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String strDateTime = "09-Jun-21 04.40.45.898000 PM";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("d-MMM-uu h.m.s.SSSSSS a", Locale.ENGLISH);
LocalDateTime ldt = LocalDateTime.parse(strDateTime, dtf);
System.out.println(ldt);
}
}
Output:
0021-06-09T16:40:45.898
ONLINE DEMO
Here, you can use y
instead of u
but I prefer u
to y
.
Learn more about the modern Date-Time API from Trail: Date Time.
Solution using the legacy API:
SimpleDateFormat does not handle fraction-of-second beyond three digits in the millisecond part correctly. You need to adjust your Date-Time string to comply with this limitation i.e. you need to remove digits from the millisecond part to keep it up to three digits. An easy way to do this is to use the Regex replacement.
Demo:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class Main {
public static void main(String[] args) throws ParseException {
String strDateTime = "09-Jun-21 04.40.45.898000 PM";
strDateTime = strDateTime.replaceAll("(.*(?<=\\.)\\d{3})(\\d+)(\\s[AP]M)", "$1$3");
SimpleDateFormat sdf = new SimpleDateFormat("d-MMM-y h.m.s.SSS a", Locale.ENGLISH);
Date date = sdf.parse(strDateTime);
System.out.println(date);
}
}
Output in my timezone:
Wed Jun 09 16:40:45 BST 2021
ONLINE DEMO
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.