Unfortunately, the accepted answer as well the other answer are wrong.
You have done two mistakes in parsing:
- You have swapped
MM
with dd
.
- You have used
H
instead of h
to parse a date-time string with AM/PM marker. The symbol, H
is used to parse a time string in 24-Hour format. Another important point to consider is that PM is written as p.m.
in Locale.CANADA
. For your time string, you can use Locale.US
which specifies it as PM.
Thus, you can use a parser like the one given below:
new SimpleDateFormat("M/d/u h:m:s a", Locale.US)
where a
has been used to parse AM/PM.
Using this parser will fix your problem but the legacy date-time API (java.util
date-time types and their formatting API, SimpleDateFormat
) is outdated and error-prone. It is recommended to stop using it completely and switch to java.time
, the modern date-time API*.
Demo using 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 convertDate = "03/19/2014 5:30:10 PM";
DateTimeFormatter dtfInput = DateTimeFormatter.ofPattern("M/d/u h:m:s a", Locale.US);
LocalDateTime ldt = LocalDateTime.parse(convertDate, dtfInput);
System.out.printf("Year: %d, Month: %d, Day: %d%n", ldt.getYear(), ldt.getMonthValue(), ldt.getDayOfMonth());
// Or, using DateTimeFormatter
DateTimeFormatter dtfOutput = DateTimeFormatter.ofPattern("'Year:' uuuu, 'Month:' M, 'Day:' d", Locale.US);
System.out.println(ldt.format(dtfOutput));
}
}
Output:
Year: 2014, Month: 3, Day: 19
Year: 2014, Month: 3, Day: 19
Learn more about the 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.