The strange codes we entered at the back are sort of like a pattern. Java will parse these to interpret how we want our date displayed.

You can see a full list of these patterns to depict different date formats in the SimpleDateFormat documentation.

Making Dates from Strings

Sometimes we’ll need our users to provide beginning or end dates for something. Conveniently, there's an HTML input field specifically for gathering dates from a user:

<input type=”date”>

This creates a handy datepicker that returns the date a user selects as a String. Cool!

But, how we change this String from our HTML input field into a proper Java Date object? Like so, using the SimpleDateFormatter in “reverse”. We’ll have to parse it, and catch the parseException so we don’t have a runtime error in case something happens that we don’t expect:

Now our string is a Date. But notice we had to create a separate SimpleDateFormatter to format the date to match our earlier example.

Comparing Dates

But what about comparing dates? Say, if we needed to know whether a library book is overdue? Conveniently, Java has built-in after() and before() methods that return true or false, and you can use to compare two dates.