String != date-time
Do not confuse a date-time object with a String that represents its value.
You should be working with objects as much as possible. Generate a String only for presentation to the user. When using strings to exchanged data with other software, use only the ISO 8601 formats.
java.time
The Question and the accepted Answer both use troublesome old legacy date-time classes, now supplanted by the java.time classes.
Your input format is not standard and is confusingly ambiguous. Is that -12:00
on the end a time zone or a time-of-day? I will guess a time-of-day. That guess means the input lacks any indication of an offset-from-UTC or a time zone. So we parse as a LocalDateTime
object.
String input = "5/5/1991-12:00"
DateTimeFormatter f = DateTimeFormatter.ofPattern( "M/d/uuuu-HH:mm" );
LocalDateTime ldt = LocalDateTime.format( input , f );
ldt.toString(): 1991-05-05T12:00
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 a time zone to give it meaning.
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(): 1991-05-05T12:00Z
The Z
on the end of a standard ISO 8601 string is short for Zulu
and UTC.
On the other hand, if the context indicates a specific time zone, apply a ZoneId
to get a ZonedDateTime
. What time zone was intended for your example input string? Did you mean noon in Auckland NZ, noon in Paris FR, or noon in Montréal Québec CA?
ZoneId z = ZoneId.of ( "America/Montreal" );
ZonedDateTime zdt = ldt.atZone ( z );
zdt.toString(): 1991-05-05T12:00-04:00[America/Montreal]
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
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.