在这里,我们演示如何使用java.text.MessageFormat该类来格式化包含时间信息的消息。
package org.nhooo.example.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 nextWeek = calendar.getTime(); // 我们希望消息为Locale.US Locale.setDefault(Locale.US); // 格式化包含日期信息的时间。 String message = MessageFormat.format("Now is {0} and the next " + "7 hours is {1}", today, nextWeek); System.out.println(message); // 格式化时间并仅显示时间部分 message = MessageFormat.format("Now is {0, time} and the next " + "7 hours is {1, time}", today, nextWeek); System.out.println(message); // 使用短格式(例如HH:mm am / pm)格式化时间 message = MessageFormat.format("Now is {0, time, short} and " + "the next 7 hours is {1, time, short}", today, nextWeek); System.out.println(message); // 使用中等格式(例如HH:mm:ss am / pm)格式化时间。 message = MessageFormat.format("Now is {0, time, medium} and " + "the next 7 hours is {1, time, medium}", today, nextWeek); System.out.println(message); // 使用长格式(例如HH:mm:ss am / pm TIMEZONE)格式化时间。 message = MessageFormat.format("Now is {0, time, long} and the " + "next 7 hours is {1, time, long}", today, nextWeek); System.out.println(message); // 使用完整格式(例如HH:mm:ss am / pm TIMEZONE)格式化时间。 message = MessageFormat.format("Now is {0, time, full} and the " + "next 7 hours is {1, time, full}", today, nextWeek); System.out.println(message); // 使用自定义模式设置时间格式。 message = MessageFormat.format("Now is {0, time, HH:mm:ss.sss} " + "and the next 7 hours is {1, time, HH:mm:ss.sss}", today, nextWeek); System.out.println(message); } }
上面的程序产生:
Now is 2/15/18, 9:07 PM and the next 7 hours is 2/16/18, 4:07 AM Now is 9:07:26 PM and the next 7 hours is 4:07:26 AM Now is 9:07 PM and the next 7 hours is 4:07 AM Now is 9:07:26 PM and the next 7 hours is 4:07:26 AM Now is 9:07:26 PM CST and the next 7 hours is 4:07:26 AM CST Now is 9:07:26 PM China Standard Time and the next 7 hours is 4:07:26 AM China Standard Time Now is 21:07:26.026 and the next 7 hours is 04:07:26.026