[問題] DateFormat.format 與 FieldPosition
DateFormat.format 可以指定 FieldPosition 來取得產生字串中特定欄位的位置。
例如
FieldPosition fp = new FieldPosition(Field.DAY_OF_MONTH);
DateFormat.format(date, buffer, fp);
這時 fp.beginIndex 與 fp.endIndex 就會存放產生字串中 天 的所在位置。
但是這個 FieldPosition 一次只能指定一個。
如果我想要取得 年 月 日 三個欄位的位置,就得寫成
FieldPosition fp1 = new FieldPosition(Field.YEAR);
FieldPosition fp2 = new FieldPosition(Field.MONTH);
FieldPosition fp3 = new FieldPosition(Field.DAY_OF_MONTH);
DateFormat.format(date, buffer, fp1);
DateFormat.format(date, new StringBuffer(), fp2);
DateFormat.format(date, new StringBuffer(), fp3);
數據是有了,但日期字串被 format 三次,不太經濟,感覺也很怪。
有比較合理的其他寫法嗎?
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 220.133.0.170
※ 編輯: kikiapple 來自: 220.133.0.170 (02/02 17:14)
討論串 (同標題文章)
以下文章回應了本文:
完整討論串 (本文為第 1 之 2 篇):