Lesson Wednesday

Another important topic we’ll eventually need to understand is working with dates in Java. As you might imagine, dates are indispensable for all kinds of things. Here are just a few examples:

  • Adding a due date for a library book
  • Adding a completion date for a to do list item
  • Setting a timer to do something after a certain amount of time has passed
  • Creating a calendar of some sort
  • Printing out a receipt for a purchase

(...And about 3 billionty things more!)

So, let's take a moment to practice working with time in Java. Create a new application in IntelliJ. Name it whatever you’d like.

Working with Dates

In our new project we'll create a class called App, and enter the following code into its main() method:

//Example One
public static void main(String args[]) {
  // new Date object
  Date newDate = new Date();
  // display time and date using toString()

When we run this app, we should see something like this printed to the console:

July 07 09:51:52 PST 2017

Cool. That was actually pretty easy, right? But this output isn’t particularly useful. Wouldn't it be a little more human-friendly if it looked something like this, instead?:

Friday, July 7th at 9:51

Can we do that? Sure we can! Let's try updating our code to look like this:

// Example Two
import java.text.SimpleDateFormat;

public static void main(String args[]) {
  Date secondDate = new Date();
  SimpleDateFormat sdf = new SimpleDateFormat ("E, MMMM d 'at' hh:mm a"); //formatter pattern
  System.out.println("Current Date: " + sdf.format(secondDate)); //apply pattern to data

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:

// Example Three
  String startDateString = "07/7/2017";
  DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
  Date startDate;
  try {
    startDate = df.parse(startDateString);
    SimpleDateFormat ft = new SimpleDateFormat ("E, MMMM d"); //formatter pattern
    System.out.println("Date that was formerly a String, formatted: " + ft.format(startDate));
  } catch (ParseException e) {

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.

Let’s make a String into a Date and compare it to today.

  //Example Four
  import java.text.SimpleDateFormat;

  String earlierDateString = "07/7/2015";
  DateFormat nextdf = new SimpleDateFormat("MM/dd/yyyy");
  Date earlierDate = new Date();

  try {
    earlierDate = nextdf.parse(earlierDateString); //overwrite date we had to initialize above
  } catch (ParseException e) {
  Date currentDate = new Date();
  boolean isTodayAfterEarlierDate = earlierDate.after(currentDate);
  System.out.println("Earlier date is after current date: " + isTodayAfterEarlierDate);

We should see the output Earlier date is after current date: false in our Console.