java.text包中的Formatter使用

import java.text.MessageFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class FormatterTest
{

    public static void main (String[] args)
    {
        System.out.println("--------Number---------");
        Locale locale = Locale.CHINA;
        String string = NumberFormat.getCurrencyInstance(locale).format(123.45);
        System.out.println(string);
        
        String string2 = NumberFormat.getPercentInstance(locale).format(0.45);
        System.out.println(string2);
        
        String time = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        System.out.println(time);
        
        System.out.println("--------Message---------");
        Object[] params = new Object[]{0.23, new Integer(1234),"张三"};
        String msg1 = MessageFormat.format("There are {2} a''s and {0} b''s", params);
        String msg2 = MessageFormat.format("There are {2} a''s and {0,number,currency} b''s", params);
        String msg3 = MessageFormat.format("There are {2} a''s and {0,number,percent} b''s", params);
        System.out.println(msg1);
        System.out.println(msg2);
        System.out.println(msg3);
        
        System.out.println("--------Date---------");
        Object[] paramsD = new Object[]{new Date(), new Date(0)};
        String msgD = MessageFormat.format("The time is {0,time,yyyy-MM-dd HH-mm-ss} and UTC of 0 is {1,time,HH-mm-ss}", paramsD);
        System.out.println(msgD);

    }
}

 

你可能感兴趣的:(java)