1 17 18 package org.apache.catalina.util; 19 20 import java.util.Date ; 21 22 import java.text.DateFormat ; 23 import java.text.FieldPosition ; 24 import java.text.ParsePosition ; 25 import java.text.SimpleDateFormat ; 26 27 37 public class FastDateFormat extends DateFormat { 38 DateFormat df; 39 long lastSec = -1; 40 StringBuffer sb = new StringBuffer (); 41 FieldPosition fp = new FieldPosition (DateFormat.MILLISECOND_FIELD); 42 43 public FastDateFormat(DateFormat df) { 44 this.df = df; 45 } 46 47 public Date parse(String text, ParsePosition pos) { 48 return df.parse(text, pos); 49 } 50 51 56 public StringBuffer format(Date date, StringBuffer toAppendTo, 57 FieldPosition fieldPosition) { 58 long dt = date.getTime(); 59 long ds = dt / 1000; 60 if (ds != lastSec) { 61 sb.setLength(0); 62 df.format(date, sb, fp); 63 lastSec = ds; 64 } else { 65 int ms = (int)(dt % 1000); 67 int pos = fp.getEndIndex(); 68 int begin = fp.getBeginIndex(); 69 if (pos > 0) { 70 if (pos > begin) 71 sb.setCharAt(--pos, Character.forDigit(ms % 10, 10)); 72 ms /= 10; 73 if (pos > begin) 74 sb.setCharAt(--pos, Character.forDigit(ms % 10, 10)); 75 ms /= 10; 76 if (pos > begin) 77 sb.setCharAt(--pos, Character.forDigit(ms % 10, 10)); 78 } 79 } 80 toAppendTo.append(sb.toString()); 81 return toAppendTo; 82 } 83 84 public static void main(String [] args) { 85 String format = "yyyy-MM-dd HH:mm:ss.SSS"; 86 if (args.length > 0) 87 format = args[0]; 88 SimpleDateFormat sdf = new SimpleDateFormat (format); 89 FastDateFormat fdf = new FastDateFormat(sdf); 90 Date d = new Date (); 91 92 d.setTime(1); System.out.println(fdf.format(d) + "\t" + sdf.format(d)); 93 d.setTime(20); System.out.println(fdf.format(d) + "\t" + sdf.format(d)); 94 d.setTime(500); System.out.println(fdf.format(d) + "\t" + sdf.format(d)); 95 d.setTime(543); System.out.println(fdf.format(d) + "\t" + sdf.format(d)); 96 d.setTime(999); System.out.println(fdf.format(d) + "\t" + sdf.format(d)); 97 d.setTime(1050); System.out.println(fdf.format(d) + "\t" + sdf.format(d)); 98 d.setTime(2543); System.out.println(fdf.format(d) + "\t" + sdf.format(d)); 99 d.setTime(12345); System.out.println(fdf.format(d) + "\t" + sdf.format(d)); 100 d.setTime(12340); System.out.println(fdf.format(d) + "\t" + sdf.format(d)); 101 102 final int reps = 100000; 103 { 104 long start = System.currentTimeMillis(); 105 for (int i = 0; i < reps; i++) { 106 d.setTime(System.currentTimeMillis()); 107 fdf.format(d); 108 } 109 long elap = System.currentTimeMillis() - start; 110 System.out.println("fast: " + elap + " elapsed"); 111 System.out.println(fdf.format(d)); 112 } 113 { 114 long start = System.currentTimeMillis(); 115 for (int i = 0; i < reps; i++) { 116 d.setTime(System.currentTimeMillis()); 117 sdf.format(d); 118 } 119 long elap = System.currentTimeMillis() - start; 120 System.out.println("slow: " + elap + " elapsed"); 121 System.out.println(sdf.format(d)); 122 } 123 } 124 } 125 | Popular Tags |