本示例演示如何使用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 MessageFormatDate { public static void main(String[] args) { Date today = new Date(); Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.DATE, 7); Date nextWeek = calendar.getTime(); // 我们希望消息为Locale.US Locale.setDefault(Locale.US); // 格式化日期,包括时间值 String message = MessageFormat.format("Today is {0} and next " + "week is {1}", today, nextWeek); System.out.println(message); // 格式化日期并仅显示日期部分 message = MessageFormat.format("Today is {0,date} and next " + "week is {1,date}", today, nextWeek); System.out.println(message); // 使用短格式(例如dd / MM / yyyy)格式化日期 message = MessageFormat.format("Today is {0,date,short} and " + "next week is {1,date,short}", today, nextWeek); System.out.println(message); // 使用中等格式格式化日期,显示月长名称, // 但使用两位数的日期和年份。 message = MessageFormat.format("Today is {0,date,medium} and " + "next week is {1,date,medium}", today, nextWeek); System.out.println(message); // 使用长格式格式化日期,日期两位长,一个月长 // 名称和四位数的年份。 message = MessageFormat.format("Today is {0,date,long} and " + "next week is {1,date,long}", today, nextWeek); System.out.println(message); // 使用完整格式格式化日期,与上述相同,再加上一整天 // 名称。 message = MessageFormat.format("Today is {0,date,full} and " + "next week is {1,date,full}", today, nextWeek); System.out.println(message); // 使用自定义模式设置日期格式。 message = MessageFormat.format("Today is {0,date,dd-MM-yyyy} and " + "next week is {1,date,dd-MM-yyyy}", today, nextWeek); System.out.println(message); } }
上面的程序产生:
Today is 2/15/18, 8:57 PM and next week is 2/22/18, 8:57 PM Today is Feb 15, 2018 and next week is Feb 22, 2018 Today is 2/15/18 and next week is 2/22/18 Today is Feb 15, 2018 and next week is Feb 22, 2018 Today is February 15, 2018 and next week is February 22, 2018 Today is Thursday, February 15, 2018 and next week is Thursday, February 22, 2018 Today is 15-02-2018 and next week is 22-02-2018