Sunday, March 4, 2012

How do I format a message that contains time information in Android?


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 nextWeek = calendar.getTime();
        Date[] times = new Date[]{today, nextWeek};

        //
        // 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}", times);
        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}", times);
        System.out.println(message);

        //
        // Format a time using a short format (eg. HH:mm am/pm)
        //
        message = MessageFormat.format("Now is {0, time, short} and " +
                "the next 7 hours is {1, time, short}", times);
        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}", times);
        System.out.println(message);

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

        //
        // Format a time using a full format (eg. HH:mm:ss am/pm TIMEZONE).
        //
        message = MessageFormat.format("Now is {0, time, full} and the " +
                "next 7 hours is {1, time, full}", times);
        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}", times);
        System.out.println(message);
    }
}

Below is the output.........

Now is 5/5/09 7:55 AM and the next 7 hours is 5/5/09 2:55 PM
Now is 7:55:38 AM and the next 7 hours is 2:55:38 PM
Now is 7:55 AM and the next 7 hours is 2:55 PM
Now is 7:55:38 AM and the next 7 hours is 2:55:38 PM
Now is 7:55:38 AM SGT and the next 7 hours is 2:55:38 PM SGT
Now is 7:55:38 AM SGT and the next 7 hours is 2:55:38 PM SGT
Now is  07:55:38.038 and the next 7 hours is  14:55:38.038

No comments:

Post a Comment