DateFormat类的使用
package frank; import java.lang.*; import java.util.Locale; import java.text.DateFormat; import java.util.Calendar; import java.util.Date; import static java.text.DateFormat.*; /** * DateFormat 类的使用 * */ public class App { public static void main(String[] args)throws Exception { Calendar c = Calendar.getInstance(); Date d = c.getTime(); Locale[] locales ={Locale.CHINA,Locale.US}; DateFormat[] df = new DateFormat[16]; for(int i = 0 ; i < locales.length; i++) { df[i*8] = DateFormat.getDateInstance(SHORT,locales[i]); df[i*8+1]=DateFormat.getDateInstance(MEDIUM,locales[i]); df[i*8+2]=DateFormat.getDateInstance(LONG,locales[i]); df[i*8+3]=DateFormat.getDateInstance(FULL,locales[i]); df[i*8+4]=DateFormat.getTimeInstance(SHORT,locales[i]); df[i*8+5]=DateFormat.getTimeInstance(MEDIUM,locales[i]); df[i*8+6]=DateFormat.getTimeInstance(LONG,locales[i]); df[i*8+7]=DateFormat.getTimeInstance(FULL,locales[i]); } for(int i = 0; i < locales.length ; i++) { switch(i) { case 0: { System.out.println("-----中国日期格式----"); break; } case 1: { System.out.println("-----美国日期格式----"); break; } default: { break; } } System.out.println("SHORT 格式的日期格式:"+df[i*8].format(d)); System.out.println("MEDIUM 格式的日期格式:"+df[i*8+1].format(d)); System.out.println("LONG 格式的日期格式:"+df[i*8+2].format(d)); System.out.println("FULL 格式的日期格式:"+df[i*8+3].format(d)); System.out.println("SHORT 格式的日期格式:"+df[i*8+4].format(d)); System.out.println("MEDIUM 格式的日期格式:"+df[i*8+5].format(d)); System.out.println("LONG 格式的日期格式:"+df[i*8+6].format(d)); System.out.println("FULL 格式的日期格式:"+df[i*8+7].format(d)); } /* *-----中国日期格式---- SHORT 格式的日期格式:13-10-17 MEDIUM 格式的日期格式:2013-10-17 LONG 格式的日期格式:2013年10月17日 FULL 格式的日期格式:2013年10月17日 星期四 SHORT 格式的日期格式:上午11:35 MEDIUM 格式的日期格式:11:35:04 LONG 格式的日期格式:上午11时35分04秒 FULL 格式的日期格式:上午11时35分04秒 CST -----美国日期格式---- SHORT 格式的日期格式:10/17/13 MEDIUM 格式的日期格式:Oct 17, 2013 LONG 格式的日期格式:October 17, 2013 FULL 格式的日期格式:Thursday, October 17, 2013 SHORT 格式的日期格式:11:35 AM MEDIUM 格式的日期格式:11:35:04 AM LONG 格式的日期格式:11:35:04 AM CST FULL 格式的日期格式:11:35:04 AM CST * * */ /**使用DateFormat中的parse方法**/ String str1 = "2013-08-21"; String str2 = "2013年12月10日"; System.out.println(DateFormat.getDateInstance().parse(str1)); System.out.println(DateFormat.getDateInstance(LONG).parse(str2));//str2是一个LONG样式的字符串日期,所以必须获得LONG样式的实例才能转换,不然就会异常。 } }