How do I format a message that contains time information?

Here we demonstrate how to use the java.text.MessageFormat class to format a message contains time information.

package org.kodejava.text;

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

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

        Date next7Hours = calendar.getTime();

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

        // Format a time including date information.
        String message = MessageFormat.format("Now is {0} and the next " +
                "7 hours is {1}", today, next7Hours);
        System.out.println(message);

        // Format a time and display only the time portion
        message = MessageFormat.format("Now is {0, time} and the next " +
                "7 hours is {1, time}", today, next7Hours);
        System.out.println(message);

        // Format a time using a short format (e.g. HH:mm am/pm)
        message = MessageFormat.format("Now is {0, time, short} and " +
                "the next 7 hours is {1, time, short}", today, next7Hours);
        System.out.println(message);

        // Format a time using a medium format (eg. HH:mm:ss am/pm).
        message = MessageFormat.format("Now is {0, time, medium} and " +
                "the next 7 hours is {1, time, medium}", today, next7Hours);
        System.out.println(message);

        // Format a time using a long format (e.g. HH:mm:ss am/pm TIMEZONE).
        message = MessageFormat.format("Now is {0, time, long} and the " +
                "next 7 hours is {1, time, long}", today, next7Hours);
        System.out.println(message);

        // Format a time using a full format (e.g. HH:mm:ss am/pm TIMEZONE).
        message = MessageFormat.format("Now is {0, time, full} and the " +
                "next 7 hours is {1, time, full}", today, next7Hours);
        System.out.println(message);

        // Format a time using a custom pattern.
        message = MessageFormat.format("Now is {0, time, HH:mm:ss.sss} " +
                "and the next 7 hours is {1, time, HH:mm:ss.sss}", today, next7Hours);
        System.out.println(message);
    }
}

The above program produces:

Now is 10/8/21, 9:38 PM and the next 7 hours is 10/9/21, 4:38 AM
Now is 9:38:10 PM and the next 7 hours is 4:38:10 AM
Now is 9:38 PM and the next 7 hours is 4:38 AM
Now is 9:38:10 PM and the next 7 hours is 4:38:10 AM
Now is 9:38:10 PM CST and the next 7 hours is 4:38:10 AM CST
Now is 9:38:10 PM China Standard Time and the next 7 hours is 4:38:10 AM China Standard Time
Now is  21:38:10.010 and the next 7 hours is  04:38:10.010
Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.