tl;dr
LocalDateTime.parse( "2016-09-25 17:26:12".replace( " " , "T" ) )
.atZoneSameInstant( ZoneId.systemDefault() )
.format( DateTimeFormatter.ofLocalizedDateTime( FormatStyle.MEDIUM ) )
Avoid legacy date-time classes
You are using troublesome old date-time classes bundled with the earliest versions of Java. Now supplanted by the java.time classes.
ISO 8601
You input string nearly complies with the standard ISO 8601 format used by default with the java.time classes. Replace the SPACE in the middle with a T
.
String input = "2016-09-25 17:26:12".replace( " " , "T" );
LocalDateTime
The input lacks any indication of offset-from-UTC or time zone. So we parse as a LocalDateTime
.
LocalDateTime ldt = LocalDateTime.parse( input );
OffsetDateTime
You claim to know from the context of your app that this date-time value was intended to be UTC. So we assign that offset as the constant ZoneOffset.UTC
to become a OffsetDateTime
.
OffsetDateTime odt = ldt.atOffset( ZoneOffset.UTC );
ZonedDateTime
You also say you want to adjust this value into the current default time zone of the user’s JVM (or Android runtime in this case). Know that this default can change at any time during your app’s execution. If the time zone is critical, you should explicitly ask the user for a desired/expected time zone. The ZoneId
class represents a time zone.
ZoneId z = ZoneId.systemDefault(); // Or, for example: ZoneId.of( "America/Montreal" )
ZonedDateTime zdt = odt.atZoneSameInstant( z );
Generate string
And you say you want to generate a string to represent this date-time value. You can specify any format you desire. But generally best to let java.time automatically localize for you according to the human language and cultural norms defined in a Locale
object. Use FormatStyle
to specify length or abbreviation (FULL
, LONG
, MEDIUM
, SHORT
).
Locale locale = Locale.getDefault(); // Or, for example: Locale.CANADA_FRENCH
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.MEDIUM ).withLocale( locale );
String output = zdt.format( f );
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old date-time classes such as java.util.Date
, .Calendar
, & java.text.SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.
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…).
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.