Java 的格式轉(zhuǎn)換(FieldPosition,ParsePosition)

package net.zcmusicbox.yeah.test.text.format;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.FieldPosition;
import java.text.NumberFormat;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;

public class SetEndIndex {
public static void main(String args[]) throws Exception {
NumberFormat numForm = NumberFormat.getInstance();
StringBuffer dest1 = new StringBuffer();
FieldPosition pos = new FieldPosition(NumberFormat.INTEGER_FIELD);
BigDecimal bd1 = new BigDecimal(2.342323232323D);
dest1 = numForm.format(bd1, dest1, pos);
System.out.println("dest1 = " + dest1);
System.out.println("INTEGER portion is at: " + pos.getBeginIndex() + ", " + pos.getEndIndex());
pos = new FieldPosition(NumberFormat.FRACTION_FIELD);
StringBuffer dest2 = new StringBuffer();
dest2 = numForm.format(bd1, dest2, pos);
System.out.println("dest2 = " + dest2);
System.out.println("FRACTION portion is at: " + pos.getBeginIndex() + ", " + pos.getEndIndex());

    DateFormat df = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG);  
    StringBuffer dest3 = new StringBuffer();  


    //關(guān)注的是幾號  
    pos = new FieldPosition(DateFormat.DATE_FIELD);  


    dest3 = df.format(new Date(), dest3, pos);  
    System.out.println("dest3 = " + dest3);  
    //結(jié)果當(dāng)前時間為2012年6月27日 下午04時06分56秒  則beginIndex為7 endIndex為9  
    System.out.println("FRACTION portion is at: " + pos.getBeginIndex() + ", " + pos.getEndIndex());  

    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");  
    String input[] = { "abc 2013-10-01 Vancouver, B.C.", "1248-03-01 Ottawa, ON", "1323-06-06 Toronto, ON" };  
    for (int i = 0; i < input.length; i++) {  



        ParsePosition pp = new ParsePosition(4);//從第四位開始處理  


        Date d = formatter.parse(input[i], pp);  
        if (d == null) {  
            //結(jié)果只處理了"abc 2013-10-01 Vancouver, B.C."   
            //"1248-03-01 Ottawa, ON"從第四位開始是"8-03-01 Ottawa, ON"無法轉(zhuǎn)換  
            System.err.println("Invalid date in " + input[i]);  
            continue;  
        }  
        //成功轉(zhuǎn)換后ParsePosition.getIndex()就是匹配的字符串結(jié)尾的索引  
        String location = input[i].substring(pp.getIndex());  
        System.out.println(" on " + d + " in " + location);  

    }  
}  

}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容