KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > JSci > text > TimeFormat


1 package JSci.text;
2
3 import java.text.*;
4 import java.util.Date JavaDoc;
5
6 /**
7 * The TimeFormat class formats a number as a date string,
8 * by first scaling the number and adding an offset,
9 * and then treating the result as a time in milliseconds.
10 * @version 1.0
11 * @author Mark Hale
12 */

13 public final class TimeFormat extends NumberFormat {
14         private DateFormat dateFormat;
15         private double scale;
16         private long offset;
17
18         /**
19          * Constructs a TimeFormat object.
20          * @param offset in milliseconds.
21          */

22         public TimeFormat(DateFormat dateFormat, double scale, long offset) {
23                 this.dateFormat = dateFormat;
24                 this.scale = scale;
25                 this.offset = offset;
26         }
27         private Date JavaDoc toDate(double x) {
28                 return new Date JavaDoc(((long)(scale*x))+offset);
29         }
30         /**
31          */

32         public StringBuffer JavaDoc format(double number, StringBuffer JavaDoc toAppendTo, FieldPosition pos) {
33                 pos.setBeginIndex(-1);
34                 pos.setEndIndex(-1);
35                 return toAppendTo.append(dateFormat.format(toDate(number)));
36         }
37         public StringBuffer JavaDoc format(long number, StringBuffer JavaDoc toAppendTo, FieldPosition pos) {
38                 pos.setBeginIndex(-1);
39                 pos.setEndIndex(-1);
40                 return toAppendTo.append(dateFormat.format(toDate(number)));
41         }
42         private Number JavaDoc toNumber(Date JavaDoc date) {
43                 return new Double JavaDoc((date.getTime()-offset)/scale);
44         }
45         public Number JavaDoc parse(String JavaDoc text, ParsePosition parsePosition) {
46                 return toNumber(dateFormat.parse(text, parsePosition));
47         }
48 }
49
50
Popular Tags