Here’s the modern answer. The other answers were fine answers when they were written in 2013. The year after that the modern date and time API came out as a replacement for the old classes Date
, SimpleDateFormat
and friends. IMHO you should use the new classes now. They are much more programmer friendly.
LocalDateTime newDate = null;
String dateTime = "2013-03-18 08:30";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm", Locale.ENGLISH);
try {
newDate = LocalDateTime.parse(dateTime, dtf);
} catch (DateTimeParseException e) {
throw new InvalidInputException("Invalid date input.");
}
Except for the class names it’s not that different from the old code. With other examples there will be differences, typically the modern classes will provide for clearer code and fewer opportunities for errors.
For just one little demonstration of a difference, let’s try the format pattern string you had with uppercase YYYY
in it:
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("YYYY-MM-dd HH:mm", Locale.ENGLISH);
Now the code throws a java.time.format.DateTimeParseException: Text '2013-03-18 08:30' could not be parsed: Unable to obtain LocalDateTime from TemporalAccessor: {MonthOfYear=3, DayOfMonth=18, WeekBasedYear[WeekFields[SUNDAY,1]]=2013},ISO resolved to 08:30 of type java.time.format.Parsed
. It’s long, I know. The thing to note is that there is no year among the fields it mentions, only a WeekBasedYear. It’s not the same; and you may have figured out by now that this is exactly because uppercase Y
is for week-based year (only usseful with a week number), where you should use lowercase y
for year. I consider this behaviour a bit more helpful than what the old classes did: they gave you a result that was wrong, pretended everything was fine and left you completely in the dark about what was wrong.
Next I understand that you want to store your date-time to a database. In the old days you would convert to some appropriate java.sql
type. No longer necessary. I believe with a JDBC 4.2 driver you can just do:
ps.setObject(3, newDate);
I have not tested this with a database, though. Note that you use setObject()
instead of setDate()
.
java.sql.Date
is for a date only, meant for the date datatype of SQL. From the docs: “To conform with the definition of SQL DATE, the millisecond values wrapped by a java.sql.Date instance must be 'normalized' by setting the hours, minutes, seconds, and milliseconds to zero in the particular time zone with which the instance is associated.” – Brandes