01: /*
02: * Created on 27-May-2006
03: */
04: package uk.org.ponder.dateutil;
05:
06: import java.text.DateFormat;
07: import java.text.DecimalFormat;
08: import java.text.ParseException;
09: import java.util.Calendar;
10: import java.util.Date;
11: import java.util.GregorianCalendar;
12:
13: import uk.org.ponder.util.UniversalRuntimeException;
14:
15: public class DateUtil {
16: public static Date makeLater(Date olddate, Date newdate) {
17: if (newdate == null)
18: return olddate;
19: if (olddate == null || olddate.before(newdate))
20: return newdate;
21: return olddate;
22: }
23:
24: public static String[] twoDigitList(int first, int last, int step) {
25: int count = (last - first) / step + 1;
26: String[] togo = new String[count];
27: DecimalFormat format = new DecimalFormat("00");
28: int val = first;
29: for (int i = 0; i < count; ++i) {
30: togo[i] = format.format(val);
31: val += step;
32: }
33: return togo;
34: }
35:
36: public static String[] twoDigitList(int first, int last) {
37: return twoDigitList(first, last, 1);
38: }
39:
40: /** Returns a "maximum length" list of days, currently simply 01..31 **/
41: public static String[] dayList() {
42: Calendar c = new GregorianCalendar();
43: int maxDay = c.getMaximum(Calendar.DAY_OF_MONTH);
44: return twoDigitList(1, maxDay);
45: }
46:
47: public static Date parse(DateFormat parser, String datestring) {
48: try {
49: return parser.parse(datestring);
50: } catch (ParseException e) {
51: throw UniversalRuntimeException.accumulate(e,
52: "Error parsing date " + datestring);
53: }
54: }
55:
56: /**
57: * Takes the Date-defining fields from the source and applies them onto the
58: * target, preserving its Time-defining fields, or the reverse
59: */
60: public static void applyFields(Date datetarget, Date datesource,
61: int fields) {
62: // This *should* be a TZ-independent operation.
63: DateFormat breaker = LocalSDF.breakformat.get();
64: String breaktarget = breaker.format(datetarget);
65: String breaksource = breaker.format(datesource);
66: String fused = fields == DateUtil.DATE_FIELDS ? breaksource
67: .substring(0, 8)
68: + breaktarget.substring(8) : breaktarget
69: .substring(0, 8)
70: + breaksource.substring(8);
71: Date newtarget = parse(breaker, fused);
72: datetarget.setTime(newtarget.getTime());
73: }
74:
75: public static final int TIME_FIELDS = 1;
76: public static final int DATE_FIELDS = 2;
77: }
|