Simple Date Format in Java

Dates and calendars have long been a challenge for Java programmers. One ray of sunshine in dealing with dates and times has been the SimpleDateFormat class found in the java.text package. The SimpleDateFormat class allows easy conversion of custom formatted Strings to Dates and Dates to custom formatted Strings.

The main use case for the SimpleDateFormat class in real-world is for converting formats between different countries and when processing forms or data. Also, the SimpleDateFormat class is great for formatting times as well as dates.

SimpleDateFormat Example

SimpleDateFormat uses letter patterns to describe the positions of time and date values. Each letter in the letter pattern represents a type of time or date value, such as a minute placeholder, or a day of the week placeholder. The most common letters seen in use with SimpleDateFormat are y for year, M for month, d for date, H for hour, m for minutes, and s for seconds. White space, forward slashes (/), colons (:), and periods (.) have no special meaning in the SimpleDateFormat‘s patterns, so are preserved as-is. If you wanted to specify a date an time using the above mentioned letter patterns, you might do so as:

MM/dd/yyyy HH:mm:ss

That format results in a date time such as:

10/01/1992 03:10:40

Here is an example of using the SimpleDateFormat class. First create the patterns as String objects. Next, construct SimpleDateFormat objects using the letter pattern strings. Finally, you can parse() strings or format() Date objects based off the letter patterns used to construct the SimpleDateFormat instances.

package net.javajdk;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateFormatting {

  public static void main(String[] args) {
		
    //October 31, 2015
    String usDate = "10/31/15";
		
    //Date letter pattern for USA dates
    String usPattern = "MM/dd/yy";
		
    //Date letter pattern for European dates
    String europeanPattern = "dd.MM.yy";
		
    // setting up the two date formats
    SimpleDateFormat sdfEurope = 
      new SimpleDateFormat( europeanPattern );
		
    SimpleDateFormat sdfUSA = 
      new SimpleDateFormat( usPattern );
	
    // preparing to get a parsed date
    Date halloween = null;
	
    //parsing Halloween's date
    //and storing it in a Date object
    try {
      halloween = sdfUSA.parse( usDate );
    } catch (ParseException e) {
      e.printStackTrace();
    }
	
    // parsing the Date object
    //into Europe friendly format
    String europeReadable = sdfEurope.format( halloween );

    System.out.println( europeReadable );
  }
}

The output would be as follows.

31.10.15

Not much to it, really.

Formatting Today’s Date

Suppose you need to auto-populate today’s date in file you are writing to disk or an email you are sending out. That is another easy task for SimpleDateFormat objects.

package net.javajdk;

import java.text.SimpleDateFormat;
import java.util.Date;

public class TodaysDate {

  public static void main(String[] args) {
    
    // setting the date format
    String dateFormat = "MM/dd/yy";
    
    // creating the formatter
    SimpleDateFormat simple = 
        new SimpleDateFormat(dateFormat);
    
    // getting today's date
    Date today = new Date();
    
    // converting today to human-readable form
    String formatted = simple.format(today);
    
    // printing out the result
    System.out.println(formatted);

  }

}

The output would look similar to the following.

08/03/15

Formatting Current Time

Formatting the current time is another common task for Java’s SimpleDateFormat class. Here’s an example with hour:minute:second format for time.

package net.javajdk;

import java.text.SimpleDateFormat;
import java.util.Date;

public class RightNow {

  public static void main(String[] args) {
    
    // setting the time format
    String timeFormat = "hh:mm:ss a";
    
    // creating the formatter
    SimpleDateFormat simple = 
        new SimpleDateFormat(timeFormat);
    
    // getting time right now
    Date rightNow = new Date();
    
    // converting today to human-readable form
    String formatted = simple.format(rightNow);
    
    // printing out the result
    System.out.println(formatted);

  }

}

It would look similar to the following.

10:30:27 PM

SimpleDateFormat Letter Patterns

Here is the full list of letter patterns used with SimpleDateFormat, in case you have an obscure format you need to parse or print.

Pattern Description
d Date
M Month displayed according to context
y Year
m Minute of hour
s Second of minute
G Era (BC/AD)
Y Calendar year the week mostly falls in.
L Month in standalone format
w Week of year
W Week of month
D Day of year
F Day of week
E Day name
u Day number meaning 1 = Monday, 2 = Tuesday, … (etc)
a AM/PM marker
H Zero based hour of day (0-23)
k One based hour of day (1-24)
K Zero based hour in AM/PM (0-11)
h One based hour in AM/PM (1-12)
S Millisecond
z Time zone
Z Time zone
X Time zone