All of the Answers using java.util.Date
and java.text.DateFormat
/.SimpleDateFormat
are outmoded. Those old date-time classes are poorly designed, confusing, and troublesome. Avoid them.
java.time
The java.time framework is built into Java 8 and later. A vast improvement over the old date-time classes.
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (see How to use…).
First, replace the SPACE in the middle of your input string with a T
to conform with the ISO 8601 standard. These standard formats are used by default in the java.time classes when parsing/generating strings.
String input = "2016-02-29 18:31:51".replace( " " , "T" );
Parse as a LocalDateTime
. The “Local” means not associated with any time zone. So this is not an actual moment on the timeline. But apparently not an issue in the context of this Question.
LocalDateTime ldt = LocalDateTime.parse( input );
Now you can ask for your various pieces as needed by calling the various getter methods. These methods return an int
primitive which you can, of course, convert to String values.