How do I format a date-time value?

In the DateFormat class there are some predefined constants that we can use to format a date time value. Here is an example of it.

package org.kodejava.example.text;

import java.text.DateFormat;
import java.util.Date;

public class DefaultDateFormatExample {
    public static void main(String[] args) {
        Date date = new Date();

        // Format date in a short format
        String today = DateFormat.getDateTimeInstance(DateFormat.SHORT,
                DateFormat.SHORT).format(date);
        System.out.println("Today " + today);

        // Format date in a medium format
        today = DateFormat.getDateTimeInstance(DateFormat.MEDIUM,
                DateFormat.MEDIUM).format(date);
        System.out.println("Today " + today);

        // Format date in a long format
        today = DateFormat.getDateTimeInstance(DateFormat.LONG,
                DateFormat.LONG).format(date);
        System.out.println("Today " + today);
    }
}

And you’ll see the result as follow:

Today 12/2/07 8:17 AM
Today Dec 2, 2007 8:17:09 AM
Today December 2, 2007 8:17:09 AM ICT

How do I format a date into dd/mm/yyyy?

Formatting a display is a common requirement when creating a program. Information in a good format can be seen as an added value to the user of the program. Using Java SimpleDateFormat we can easily format a date in our program.

package org.kodejava.example.text;

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

public class DateFormatExample {
    public static void main(String[] args) {
        Date date = Calendar.getInstance().getTime();

        // Display a date in day, month, year format
        DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
        String today = formatter.format(date);
        System.out.println("Today : " + today);

        // Display date with day name in a short format
        formatter = new SimpleDateFormat("EEE, dd/MM/yyyy");
        today = formatter.format(date);
        System.out.println("Today : " + today);

        // Display date with a short day and month name
        formatter = new SimpleDateFormat("EEE, dd MMM yyyy");
        today = formatter.format(date);
        System.out.println("Today : " + today);

        // Formatting date with full day and month name and show time up to
        // milliseconds with AM/PM
        formatter = new SimpleDateFormat("EEEE, dd MMMM yyyy, hh:mm:ss.SSS a");
        today = formatter.format(date);
        System.out.println("Today : " + today);
    }
}

Let’s view what we got on the console:

Today : 02/12/2007
Today : Sun, 02/12/2007
Today : Sun, 02 Dec 2007
Today : Sunday, 02 December 2007, 08:03:17.828 AM

How do I convert string of time to time object?

You want to convert a string representing a time into a time object in Java. As we know that Java represents a time information in a class java.util.Date, this class keep information for date and time.

Now if you have a string of time like 15:30:18, you can use a SimpleDateFormat object to parse the string time and return a java.util.Date object. The pattern of the string should be passed to the SimpleDateFormat constructor. In the example below the string is formatted as hh:mm:ss (hour:minute:second).

package org.kodejava.example.util;

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

public class StringToTimeExample {
    public static void main(String[] args) {        
        // A string of time information
        String time = "15:30:18";

        // Create an instance of SimpleDateFormat with the specified
        // format.
        DateFormat sdf = new SimpleDateFormat("hh:mm:ss");
        try {
            // To get the date object from the string just called the 
            // parse method and pass the time string to it. This method 
            // throws ParseException if the time string is invalid. 
            // But remember as we don't pass the date information this 
            // date object will represent the 1st of january 1970.
            Date date = sdf.parse(time);            
            System.out.println("Date and Time: " + date);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

How do I convert Date to String?

package org.kodejava.example.util;

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

public class DateToString {
    public static void main(String[] args) {
        // Create an instance of SimpleDateFormat used for formatting 
        // the string representation of date (month/day/year)
        DateFormat df = new SimpleDateFormat("MM/dd/yyyy");

        // Get the date today using Calendar object.
        Date today = Calendar.getInstance().getTime();        
        // Using DateFormat format method we can create a string 
        // representation of a date with the defined format.
        String reportDate = df.format(today);

        // Print what date is today!
        System.out.println("Report Date: " + reportDate);
    }
}

How do I convert String to Date object in Java?

The following code shows how we can convert a string representation of date into java.util.Date object.

To convert a string of date we can use the help from java.text.SimpleDateFormat that extends java.text.DateFormat abstract class.

package org.kodejava.example.text;

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

public class ConvertStringToDateExample {
    public static void main(String[] args) {
        DateFormat df = new SimpleDateFormat("dd/MM/yyyy");

        try {
            Date today = df.parse("20/12/2005");
            System.out.println("Today = " + df.format(today));
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}

And here is the result of our code:

Today = 20/12/2005

The example starts by creating an instance of SimpleDateFormat with dd/MM/yyyy format which mean that the date string is formatted in day-month-year sequence.

Finally using the parse(String source) method we can get the Date instance. Because parse method can throw java.text.ParseException exception if the supplied date is not in a valid format; we need to catch it.

Here are the list of defined patterns that can be used to format the date taken from the Java class documentation.

Letter Date / Time Component Examples
G Era designator AD
y Year 1996; 96
M Month in year July; Jul; 07
w Week in year 27
W Week in month 2
D Day in year 189
d Day in month 10
F Day of week in month 2
E Day in week Tuesday; Tue
a Am/pm marker PM
H Hour in day (0-23) 0
k Hour in day (1-24) 24
K Hour in am/pm (0-11) 0
h Hour in am/pm (1-12) 12
m Minute in hour 30
s Second in minute 55
S Millisecond 978
z Time zone Pacific Standard Time; PST; GMT-08:00
Z Time zone -0800