1 7 8 package com.ibm.icu.util; 9 10 import java.util.Date ; 11 12 17 public class SimpleDateRule implements DateRule 18 { 19 27 public SimpleDateRule(int month, int dayOfMonth) 28 { 29 this.month = month; 30 this.dayOfMonth = dayOfMonth; 31 this.dayOfWeek = 0; 32 } 33 34 SimpleDateRule(int month, int dayOfMonth, Calendar cal) 36 { 37 this.month = month; 38 this.dayOfMonth = dayOfMonth; 39 this.dayOfWeek = 0; 40 this.calendar = cal; 41 } 42 43 55 public SimpleDateRule(int month, int dayOfMonth, int dayOfWeek, boolean after) 56 { 57 this.month = month; 58 this.dayOfMonth = dayOfMonth; 59 this.dayOfWeek = after ? dayOfWeek : -dayOfWeek; 60 } 61 62 75 public Date firstAfter(Date start) 76 { 77 return doFirstBetween(start, null); 78 } 79 80 95 public Date firstBetween(Date start, Date end) 96 { 97 return doFirstBetween(start, end); 99 } 100 101 113 public boolean isOn(Date date) 114 { 115 Calendar c = calendar; 116 117 synchronized(c) { 118 c.setTime(date); 119 120 int dayOfYear = c.get(Calendar.DAY_OF_YEAR); 121 122 c.setTime(computeInYear(c.get(Calendar.YEAR), c)); 123 124 127 return c.get(Calendar.DAY_OF_YEAR) == dayOfYear; 128 } 129 } 130 131 137 public boolean isBetween(Date start, Date end) 138 { 139 return firstBetween(start, end) != null; } 141 142 private Date doFirstBetween(Date start, Date end) 143 { 144 Calendar c = calendar; 145 146 synchronized(c) { 147 c.setTime(start); 148 149 int year = c.get(Calendar.YEAR); 150 int month = c.get(Calendar.MONTH); 151 152 if (month > this.month) { 155 year++; 156 } 157 158 Date result = computeInYear(year, c); 160 161 if (month == this.month && result.before(start)) { 164 result = computeInYear(year+1, c); 165 } 166 167 if (end != null && result.after(end)) { 168 return null; 169 } 170 return result; 171 } 172 } 173 174 private Date computeInYear(int year, Calendar c) 175 { 176 synchronized(c) { 177 c.clear(); 178 c.set(Calendar.ERA, c.getMaximum(Calendar.ERA)); 179 c.set(Calendar.YEAR, year); 180 c.set(Calendar.MONTH, month); 181 c.set(Calendar.DATE, dayOfMonth); 182 183 185 if (dayOfWeek != 0) { 186 c.setTime(c.getTime()); int weekday = c.get(Calendar.DAY_OF_WEEK); 188 189 192 int delta = 0; 193 if (dayOfWeek > 0) { 194 delta = (dayOfWeek - weekday + 7) % 7; 197 } 198 else { 199 delta = -((dayOfWeek + weekday + 7) % 7); 202 } 203 c.add(Calendar.DATE, delta); 205 } 206 207 return c.getTime(); 208 } 209 } 210 211 215 219 private static GregorianCalendar gCalendar = new GregorianCalendar(); 220 221 private Calendar calendar = gCalendar; 222 223 private int month; 224 private int dayOfMonth; 225 private int dayOfWeek; 226 }; 227 | Popular Tags |