How to Use the parse Method in Java to Create a Date-Time Object - dummies

How to Use the parse Method in Java to Create a Date-Time Object

By Doug Lowe

One way to create a Date-Time object in Java is to use the static parse method, which creates a Date-Time object from a string that represents a specific date or time. For example, the following code creates a LocalDate object representing December 15, 2014:

LocalDate d = LocalDate.parse("2014-12-15");

To create a LocalDateTime object that represents a specific time on a specific date, use the parse method. Here’s an example that sets the time to 3:45 p.m. on December 15, 2014:

LocalDateTime dt;
dt = LocalDateTime.parse("2014-12-15T15:45");

Note that the letter T separates the date from the time, and the time is expressed in 24-hour clock format. If you need to be more precise, you can also specify seconds, as in this example:

dt = LocalDateTime.parse("2014-12-15T15:45:13.5");

Here the time is set to 13.5 seconds after 2:45 p.m.

If the string is not in the correct format, the parse method throws a DateTimeParseException. Whenever you use the parse method, you should enclose it in a try block and catch this exception, as in this example:

LocalDateTime dt;
 dt = LocalDateTime.parse("2014-12-15T03:45PM");
catch (DateTimeParseException ex)

The parse method is especially useful for converting user input to a Date-Time object. For example, you might use it along with the Scanner class to read a date from the console, or you can use parse in a Swing application to read a date from a text box.

When you do, you should prompt the user with the expected date format and catch DateTimeParseException in case the user enters the date in the wrong format.