import java.text.*;
import java.util.*;
import java.io.*;
public class NumberDateFomatEx {
public static void main(String[] args) throws Exception{
// TODO code application logic here
System.out.print("请输入任一数字(可加千分位,例如:5,678.12):");
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
String num=br.readLine();
System.out.print("请输入任一日期(例如:2008/5/1):");
isr=new InputStreamReader(System.in);
br=new BufferedReader(isr);
String dt=br.readLine();
System.out.print("请问要依照什么地区来格式化(1)北京(2)美国(3)英国?");
isr=new InputStreamReader(System.in);
br=new BufferedReader(isr);
String ic=br.readLine();
br.close();
isr.close();
NumberFormat nf_TW=NumberFormat.getInstance(Locale.TAIWAN);
DateFormat df_TW=DateFormat.getDateInstance(DateFormat.LONG,Locale.TAIWAN);
NumberFormat nf_US=NumberFormat.getInstance(Locale.US);
DateFormat df_US=DateFormat.getDateInstance(DateFormat.LONG,Locale.US);
NumberFormat nf_UK=NumberFormat.getInstance(Locale.UK);
DateFormat df_UK=DateFormat.getDateInstance(DateFormat.LONG,Locale.UK);
Number number=nf_TW.parse(num);
Date date=df_TW.parse(dt);
int localeNo=Integer.parseInt(ic);
switch(localeNo){
case 1:
System.out.print("数字:"+nf_TW.format(number));
System.out.print("时间:"+df_TW.format(date));
break;
case 2:
System.out.print("数字:"+nf_US.format(number));
System.out.print("时间:"+df_US.format(date));
break;
case 3:
System.out.print("数字:"+nf_UK.format(number));
System.out.print("时间:"+df_UK.format(date));
break;
}
}
}结果:
请输入任一数字(可加千分位,例如:5,678.12):1,254.22
请输入任一日期(例如:2008/5/1):2009/8/8
请问要依照什么地区来格式化(1)北京(2)美国(3)英国?1
Exception in thread "main" java.text.ParseException: Unparseable date: "2009/8/8"
at java.text.DateFormat.parse(DateFormat.java:337)
at NumberDateFomatEx.main(NumberDateFomatEx.java:38)Process completed.但是我如果把DateFormat.LONG改为DateFormat.SHORT之后又是正确的呢?
SHORT is completely numeric, such as 12.13.52 or 3:30pm
MEDIUM is longer, such as Jan 12, 1952
LONG is longer, such as January 12, 1952 or 3:30:32pm
FULL is pretty completely specified, such as Tuesday, April 12, 1952 AD or 3:30:42pm PST.
另外建议你把各个功能封装到方法中去,main方法过于臃肿不利于维护和调试。
也可以用SimpleDateFormat ,程序改为
NumberFormat nf_TW=NumberFormat.getInstance(Locale.TAIWAN);
SimpleDateFormat df_TW=new SimpleDateFormat("yyyy/mm/dd",Locale.TAIWAN);
NumberFormat nf_US=NumberFormat.getInstance(Locale.US);
SimpleDateFormat df_US=new SimpleDateFormat("yyyy/mm/dd",Locale.US);
NumberFormat nf_UK=NumberFormat.getInstance(Locale.UK);
SimpleDateFormat df_UK=new SimpleDateFormat("yyyy/mm/dd",Locale.UK);