Formatting a Message Containing a Date


 

Formatting a Message Containing a Date

In this section, you will learn how to format the message containing a date.

In this section, you will learn how to format the message containing a date.

Formatting a Message Containing a Date

In this section, you will learn how to format the message containing a date.

Java has also provide a way to format the message either it contains date, time or number. The class MessageFormat converts a generalized 'template' message into a case-specific message. It is a better way to abstract the general structure of a message from the actual content. These are designed  to be created for a particular format, and then reused. You can done this by using the instance method MessageFormat.format(Object args).

In the given example, we have used the instance method format() to format the message with different date styles like, short, medium, long, full. You can also format the message with date in different languages.

Here is the code:

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

public class FormattingMessageWithDate {
	public static void main(String[] args) {
		Object[] params = new Object[] { new Date(), new Date(0) };
		String msg1 = MessageFormat.format("Today is {0} and UTC is {1}",
				params);
		System.out.println(msg1);
		String msg2 = MessageFormat.format(
				"Today is {0,date} and UTC is {1,date}", params);
		System.out.println(msg2);
		String msg3 = MessageFormat.format(
				"Today is {0,date,short} and UTC is {1,date,short}", params);
		System.out.println(msg3);
		String msg4 = MessageFormat.format(
				"Today is {0,date,medium} and UTC is {1,date,medium}", params);
		System.out.println(msg4);
		String msg5 = MessageFormat.format(
				"Today is {0,date,long} and UTC is {1,date,long}", params);
		System.out.println(msg5);
		String msg6 = MessageFormat.format(
				"Today is {0,date,full} and UTC is {1,date,full}", params);
		System.out.println(msg6);
		String msg7 = MessageFormat.format(
				"Today is {0,date,MMMM dd,yyyy} and UTC is {1,date,MMMM dd,yyyy}",
						params);
		System.out.println(msg7);
	}
}

Output:

Today is 10/5/10 11:13 AM and UTC is 1/1/70 5:30 AM
Today is Oct 5, 2010 and UTC is Jan 1, 1970
Today is 10/5/10 and UTC is 1/1/70
Today is Oct 5, 2010 and UTC is Jan 1, 1970
Today is October 5, 2010 and UTC is January 1, 1970
Today is Tuesday, October 5, 2010 and UTC is Thursday, January 1, 1970
Today is October 05,2010 and UTC is January 01,1970

Ads