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
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024