You have got a wrong Date-Time string as the input.
AM/PM marker is not applicable for the 24-Hour format of time. It should be either 2012-03-17 04:00:00 PM
or 2012-03-17 16:00:00
.
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*.
Also, quoted below is a notice from the home page of Joda-Time:
Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.
Solution using java.time
, the modern Date-Time API:
Let's first try to do it the way you have done:
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String startDateTime = "2012-03-17 16:00:00 PM";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd hh:mm:ss a", Locale.ENGLISH);
LocalDateTime ldt = LocalDateTime.parse(startDateTime, dtf);
System.out.println(ldt);
}
}
Output:
Exception in thread "main" java.time.format.DateTimeParseException:
Text '2012-03-17 16:00:00 PM' could not be parsed: Invalid value for
ClockHourOfAmPm (valid values 1 - 12): 16
As you can see, the java.time
API correctly throws an exception informing you about the problem. SimpleDateFormat
, on the other hand, parses the input string erroneously.
Now, let's see how you can parse it correctly. In order to parse it correctly, we will use:
- The format,
uuuu-MM-dd HH:mm:ss
where H
specifies the 24-Hour format. For your Date-Time string, you can use y
instead of u
but I prefer u
to y
.
- The function,
DateTimeFormatter#parse(CharSequence, ParsePosition)
with the ParsePosition
index set to 0
.
Demo:
import java.text.ParsePosition;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String startDateTime = "2012-03-17 16:00:00 PM";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss", Locale.ENGLISH);
ParsePosition pp = new ParsePosition(0);
LocalDateTime ldt = LocalDateTime.from(dtf.parse(startDateTime, pp));
System.out.println(ldt);
}
}
Output:
2012-03-17T16:00
ONLINE DEMO
Note: Never use SimpleDateFormat or DateTimeFormatter without a Locale.
Learn more about the modern Date-Time API from Trail: Date Time.
* 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.