java examples
Home Java Examples Resources Java Interview Questions
Brainpower SEO

How to format a message that contains date information?

This example demonstrate how you can use the java.text.MessageFormat class to format a message with a date information in it.

package com.javacoderanch.example.text;

import java.util.Date;
import java.util.Calendar;
import java.util.Locale;
import java.text.MessageFormat;

public class MessageFormatDate {
    public static void main(String[] args) {
        Date today = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, 7);

        Date nextWeek = calendar.getTime();
        Date[] dates = new Date[] {today, nextWeek};

        //
        // We want the message to be is Locale.US
        //
        Locale.setDefault(Locale.US);

        //
        // Format a date, the time value is included
        //
        String message = MessageFormat.format("Today is {0} and next week is {1}", dates);
        System.out.println(message);

        //
        // Format a date and display only the date portion
        //
        message = MessageFormat.format("Today is {0,date} and next week is {1,date}", dates);
        System.out.println(message);

        //
        // Format a date using a short format (eg. dd/MM/yyyy)
        //
        message = MessageFormat.format("Today is {0,date,short} and next week is {1,date,short}", dates);
        System.out.println(message);

        //
        // Format a date using a medium format, it display the month long name,
        // but using a two digit date and year.
        //
        message = MessageFormat.format("Today is {0,date,medium} and next week is {1,date,medium}", dates);
        System.out.println(message);

        //
        // Format a date using a long format, two digit for date, a long month
        // name and a four digit year.
        //
        message = MessageFormat.format("Today is {0,date,long} and next week is {1,date,long}", dates);
        System.out.println(message);

        //
        // Format a date using a full format, the same as above plus a full day
        // name.
        //
        message = MessageFormat.format("Today is {0,date,full} and next week is {1,date,full}", dates);
        System.out.println(message);

        //
        // Format a date using a custom pattern.
        //
        message = MessageFormat.format("Today is {0,date,dd-MM-yyyy} and next week is {1,date,dd-MM-yyyy}", dates);
        System.out.println(message);
    }
}

The above program produces:

Today is 5/5/09 7:54 AM and next week is 5/12/09 7:54 AM
Today is May 5, 2009 and next week is May 12, 2009
Today is 5/5/09 and next week is 5/12/09
Today is May 5, 2009 and next week is May 12, 2009
Today is May 5, 2009 and next week is May 12, 2009
Today is Tuesday, May 5, 2009 and next week is Tuesday, May 12, 2009
Today is  05-05-2009 and next week is  12-05-2009