tl;dr
Use java.time in modern Java.
LocalDateTime.parse(
"07/28/2011 11:06:37 AM" ,
DateTimeFormatter.ofPattern( "MM/dd/uuuu hh:mm:ss a" ).withLocale( Locale.of( "en" , "US" ) ) ;
)
java.time
In modern Java, use java.time classes defined in JSR 310, built into Java 8+.
Define a formatting pattern to match your input string.
Use two M
characters for the month number, MM
, not three. Three is for name of month in text rather than month number.
Use the matching character for delimiter. In your input, that means SOLIDUS (slash) character rather than hyphen.
String input = "07/28/2011 11:06:37 AM";
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM/dd/uuuu hh:mm:ss a" ) ;
We also need a Locale
to specify the human language and cultural norms to be used in parsing the AM/PM.
Locale locale = Locale.of( "en" , "US" ) ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM/dd/uuuu hh:mm:ss a" ).withLocale( locale ) ;
Your input represents a date with time-of-day but lacks the context of a time zone or offset-from-UTC. So parse as a LocalDateTime
.
Be aware that your input, and the LocalDateTime
class, do not represent a moment, is not a point on the timeline. Without a zone or offset, we have no way to know if your input means 11 AM in Tokyo Japan, 11 AM in Toulouse France, or 11 AM in Toledo Ohio — three very different moments, several hours apart.
LocalDateTime ldt = LocalDateTime.parse( input , f ) ;
See this code run at Ideone.com.
ldt.toString(): 2011-07-28T11:06:37
Calendar
is not very helpful when it comes to parsing/formatting dates from/toString
. Regardless, I'd prefer Joda Time: joda-time.sourceforge.net. – Universality