Home Tutorial Java Corejava Javatext Formatting a Message Containing a Time

 
 

Formatting a Message Containing a Time
Posted on: October 9, 2010 at 12:00 AM
Advertisement
In this section, you will learn how to format a message that contains time.

Formatting a Message Containing a Time

In this section, you will learn how to format a message that contains time.

You can format the message in different ways and can make it in more readable form. Java has designed a class MessageFormat for advanced message formatting. It is having some advantage over other methods and classes like dependency on Locale and pre-compilation of the message. If the message contains any date, time or number, then also it can format the message easily in a standard way. Here, we are going to format a message which contains the time.

In the given example, we have used the instance method format() to format the message with different time styles like, short, medium, long, full.  If you want to format the message with time in different languages then you have to use the setLocale() method of MessageFormat class.

Here is the code:

import java.text.*;
import java.util.*;

public class FormattingMessageWithTime {
	public static void main(String[] args) {
		Object[] obj = new Object[] { new Date(), new Date(0) };
		String msg1 = MessageFormat.format("The time is {0} and UTC is {1}",
				obj);
		System.out.println(msg1);
		String msg2 = MessageFormat.format(
				"The time is {0,time} and UTC is {1,time}", obj);
		System.out.println(msg2);
		String msg3 = MessageFormat.format(
				"The time is {0,time,short} and UTC is {1,time,short}", obj);
		System.out.println(msg3);
		String msg4 = MessageFormat.format(
				"The time is {0,time,medium} and UTC is {1,time,medium}", obj);
		System.out.println(msg4);
		String msg5 = MessageFormat.format(
				"The time is {0,time,long} and UTC is {1,time,long}", obj);
		System.out.println(msg5);
		String msg6 = MessageFormat.format(
				"The time is {0,time,full} and UTC is {1,time,full}", obj);
		System.out.println(msg6);
		String msg7 = MessageFormat.format(
				"The time is {0,time,HH:mm:ss} and UTC is {1,time,HH:mm:ss}",
				obj);
		System.out.println(msg7);
	}
}

Output:

The time is 3:36:55 PM and UTC is 5:30:00 AM
The time is 3:36 PM and UTC is 5:30 AM
The time is 3:36:55 PM and UTC is 5:30:00 AM
The time is 3:36:55 PM GMT+05:30 and UTC is 5:30:00 AM GMT+05:30
The time is 3:36:55 PM GMT+05:30 and UTC is 5:30:00 AM GMT+05:30
The time is 15:36:55 and UTC is 05:30:00

Advertisement

Related Tags for Formatting a Message Containing a Time:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: October 9, 2010

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com