java.time
The Question and other Answers use the troublesome old legacy date-time classes bundled with the earliest versions of Java. Now supplanted by the java.time classes.
ISO 8601
By the way, use the ISO 8601 formats when generating Strings to represent date-time values for exchange with other software. Your format is ambiguous and trickier to parse, unlike the standard formats.
DateTimeFormatter
The codes defining a formatting pattern in java.time.DateTimeFormatter
are similar to the outmoded SimpleDateFormat
but not exactly. So read the doc carefully.
String input = "1/29/2014 11:45:00 AM";
Locale locale = Locale.ENGLISH; // For translating the “AM” & “PM”.
DateTimeFormatter f = DateTimeFormatter.ofPattern ( "M/d/uuuu hh:mm:ss a" ).withLocale( locale );
LocalDateTime
Your input lacks any indication of an offset-from-UTC or a time zone. So we parse as a LocalDateTime
object.
LocalDateTime ldt = LocalDateTime.parse ( input , f );
ldt.toString(): 2014-01-29T11:45
A LocalDateTime
object purposely lacks any offset-from-UTC or time zone. That means it does not represent a moment on the timeline, only a rough idea about possible moments. You must assign an offset or time zone to give it meaning.
OffsetDateTime
If the context of your suggestions indicates this input was meant to be in UTC, apply the constant ZoneOffset.UTC
to get an OffsetDateTime
.
OffsetDateTime odt = ldt.atOffset ( ZoneOffset.UTC );
odt.toString(): 2014-01-29T11:45Z
ZonedDateTime
On the other hand, if the context indicates a specific time zone, apply a ZoneId
to get a ZonedDateTime
. The Questions seems to indicate that the Europe/London
time zone is intended. Be aware that this time zone is not the same as UTC.
ZoneId z = ZoneId.of ( "Europe/London" );
ZonedDateTime zdt = ldt.atZone ( z );
zdt.toString(): 2014-01-29T11:45-05:00[America/Montreal]
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.