1. /* ===========================================================
  2. * JFreeChart : a free chart library for the Java(tm) platform
  3. * ===========================================================
  4. *
  5. * (C) Copyright 2000-2004, by Object Refinery Limited and Contributors.
  6. *
  7. * Project Info: http://www.jfree.org/jfreechart/index.html
  8. *
  9. * This library is free software; you can redistribute it and/or modify it under the terms
  10. * of the GNU Lesser General Public License as published by the Free Software Foundation;
  11. * either version 2.1 of the License, or (at your option) any later version.
  12. *
  13. * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
  14. * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  15. * See the GNU Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public License along with this
  18. * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
  19. * Boston, MA 02111-1307, USA.
  20. *
  21. * [Java is a trademark or registered trademark of Sun Microsystems, Inc.
  22. * in the United States and other countries.]
  23. *
  24. * ---------
  25. * Week.java
  26. * ---------
  27. * (C) Copyright 2001-2004, by Object Refinery Limited and Contributors.
  28. *
  29. * Original Author: David Gilbert (for Object Refinery Limited);
  30. * Contributor(s): Aimin Han;
  31. *
  32. * $Id: Week.java,v 1.5 2004/11/04 11:21:54 mungady Exp $
  33. *
  34. * Changes
  35. * -------
  36. * 11-Oct-2001 : Version 1 (DG);
  37. * 18-Dec-2001 : Changed order of parameters in constructor (DG);
  38. * 19-Dec-2001 : Added a new constructor as suggested by Paul English (DG);
  39. * 29-Jan-2002 : Worked on the parseWeek(...) method (DG);
  40. * 13-Feb-2002 : Fixed bug in Week(Date) constructor (DG);
  41. * 26-Feb-2002 : Changed getStart(), getMiddle() and getEnd() methods to evaluate with reference
  42. * to a particular time zone (DG);
  43. * 05-Apr-2002 : Reinstated this class to the JCommon library (DG);
  44. * 24-Jun-2002 : Removed unnecessary main method (DG);
  45. * 10-Sep-2002 : Added getSerialIndex() method (DG);
  46. * 06-Oct-2002 : Fixed errors reported by Checkstyle (DG);
  47. * 18-Oct-2002 : Changed to observe 52 or 53 weeks per year, consistent with GregorianCalendar.
  48. * Thanks to Aimin Han for the code (DG);
  49. * 02-Jan-2003 : Removed debug code (DG);
  50. * 13-Mar-2003 : Moved to com.jrefinery.data.time package, and implemented Serializable (DG);
  51. * 21-Oct-2003 : Added hashCode() method (DG);
  52. * 24-May-2004 : Modified getFirstMillisecond() and getLastMillisecond() to take account of
  53. * firstDayOfWeek setting in Java's Calendar class (DG);
  54. * 30-Sep-2004 : Replaced getTime().getTime() with getTimeInMillis() (DG);
  55. * 04-Nov-2004 : Reverted change of 30-Sep-2004, because it won't work for JDK 1.3 (DG);
  56. *
  57. */
  58. package org.jfree.data.time;
  59. import java.io.Serializable;
  60. import java.util.Calendar;
  61. import java.util.Date;
  62. import java.util.TimeZone;
  63. /**
  64. * A calendar week. All years are considered to have 53 weeks, numbered from 1 to
  65. * 53, although in many cases the 53rd week is empty. Most of the time, the 1st week
  66. * of the year *begins* in the previous calendar year, but it always finishes in the current
  67. * year (this behaviour matches the workings of the <code>GregorianCalendar</code> class).
  68. * <P>
  69. * This class is immutable, which is a requirement for all {@link RegularTimePeriod} subclasses.
  70. */
  71. public class Week extends RegularTimePeriod implements Serializable {
  72. /** Constant for the first week in the year. */
  73. public static final int FIRST_WEEK_IN_YEAR = 1;
  74. /** Constant for the last week in the year. */
  75. public static final int LAST_WEEK_IN_YEAR = 53;
  76. /** The year in which the week falls. */
  77. private Year year;
  78. /** The week (1-53). */
  79. private int week;
  80. /**
  81. * Creates a new time period for the week in which the current system date/time falls.
  82. */
  83. public Week() {
  84. this(new Date());
  85. }
  86. /**
  87. * Creates a time period representing the week in the specified year.
  88. *
  89. * @param week the week (1 to 53).
  90. * @param year the year (1900 to 9999).
  91. */
  92. public Week(int week, int year) {
  93. this(week, new Year(year));
  94. }
  95. /**
  96. * Creates a time period representing the week in the specified year.
  97. *
  98. * @param week the week (1 to 53).
  99. * @param year the year (1900 to 9999).
  100. */
  101. public Week(int week, Year year) {
  102. if ((week < FIRST_WEEK_IN_YEAR) && (week > LAST_WEEK_IN_YEAR)) {
  103. throw new IllegalArgumentException("The 'week' argument must be in the range 1 - 53.");
  104. }
  105. this.week = week;
  106. this.year = year;
  107. }
  108. /**
  109. * Creates a time period for the week in which the specified date/time falls.
  110. *
  111. * @param time the time (<code>null</code> not permitted).
  112. */
  113. public Week(Date time) {
  114. // defer argument checking...
  115. this(time, RegularTimePeriod.DEFAULT_TIME_ZONE);
  116. }
  117. /**
  118. * Creates a time period for the week in which the specified date/time falls, calculated
  119. * relative to the specified time zone.
  120. *
  121. * @param time the date/time (<code>null</code> not permitted).
  122. * @param zone the time zone (<code>null</code> not permitted).
  123. */
  124. public Week(Date time, TimeZone zone) {
  125. if (time == null) {
  126. throw new IllegalArgumentException("Null 'time' argument.");
  127. }
  128. if (zone == null) {
  129. throw new IllegalArgumentException("Null 'zone' argument.");
  130. }
  131. Calendar calendar = Calendar.getInstance(zone);
  132. calendar.setTime(time);
  133. // sometimes the last few days of the year are considered to fall in the *first* week of
  134. // the following year. Refer to the Javadocs for GregorianCalendar.
  135. int tempWeek = calendar.get(Calendar.WEEK_OF_YEAR);
  136. if (tempWeek == 1 && calendar.get(Calendar.MONTH) == Calendar.DECEMBER) {
  137. this.week = 1;
  138. this.year = new Year(calendar.get(Calendar.YEAR) + 1);
  139. }
  140. else {
  141. this.week = Math.min(tempWeek, LAST_WEEK_IN_YEAR);
  142. this.year = new Year(calendar.get(Calendar.YEAR));
  143. }
  144. }
  145. /**
  146. * Returns the year in which the week falls.
  147. *
  148. * @return The year (never <code>null</code>).
  149. */
  150. public Year getYear() {
  151. return this.year;
  152. }
  153. /**
  154. * Returns the year in which the week falls, as an integer value.
  155. *
  156. * @return The year.
  157. */
  158. public int getYearValue() {
  159. return this.year.getYear();
  160. }
  161. /**
  162. * Returns the week.
  163. *
  164. * @return The week.
  165. */
  166. public int getWeek() {
  167. return this.week;
  168. }
  169. /**
  170. * Returns the week preceding this one. This method will return <code>null</code> for some
  171. * lower limit on the range of weeks (currently week 1, 1900). For week 1 of any year, the
  172. * previous week is always week 53, but week 53 may not contain any days (you should
  173. * check for this).
  174. *
  175. * @return The preceding week (possibly <code>null</code>).
  176. */
  177. public RegularTimePeriod previous() {
  178. Week result;
  179. if (this.week != FIRST_WEEK_IN_YEAR) {
  180. result = new Week(this.week - 1, this.year);
  181. }
  182. else {
  183. // we need to work out if the previous year has 52 or 53 weeks...
  184. Year prevYear = (Year) this.year.previous();
  185. if (prevYear != null) {
  186. int yy = prevYear.getYear();
  187. Calendar prevYearCalendar = Calendar.getInstance();
  188. prevYearCalendar.set(yy, Calendar.DECEMBER, 31);
  189. result = new Week(
  190. prevYearCalendar.getActualMaximum(Calendar.WEEK_OF_YEAR), prevYear
  191. );
  192. }
  193. else {
  194. result = null;
  195. }
  196. }
  197. return result;
  198. }
  199. /**
  200. * Returns the week following this one. This method will return <code>null</code> for some
  201. * upper limit on the range of weeks (currently week 53, 9999). For week 52 of any year,
  202. * the following week is always week 53, but week 53 may not contain any days (you should
  203. * check for this).
  204. *
  205. * @return The following week (possibly <code>null</code>).
  206. */
  207. public RegularTimePeriod next() {
  208. Week result;
  209. if (this.week < 52) {
  210. result = new Week(this.week + 1, this.year);
  211. }
  212. else {
  213. Calendar calendar = Calendar.getInstance();
  214. calendar.set(this.year.getYear(), Calendar.DECEMBER, 31);
  215. int actualMaxWeek = calendar.getActualMaximum(Calendar.WEEK_OF_YEAR);
  216. if (this.week != actualMaxWeek) {
  217. result = new Week(this.week + 1, this.year);
  218. }
  219. else {
  220. Year nextYear = (Year) this.year.next();
  221. if (nextYear != null) {
  222. result = new Week(FIRST_WEEK_IN_YEAR, nextYear);
  223. }
  224. else {
  225. result = null;
  226. }
  227. }
  228. }
  229. return result;
  230. }
  231. /**
  232. * Returns a serial index number for the week.
  233. *
  234. * @return The serial index number.
  235. */
  236. public long getSerialIndex() {
  237. return this.year.getYear() * 53L + this.week;
  238. }
  239. /**
  240. * Returns the first millisecond of the week, evaluated using the supplied
  241. * calendar (which determines the time zone).
  242. *
  243. * @param calendar the calendar.
  244. *
  245. * @return The first millisecond of the week.
  246. */
  247. public long getFirstMillisecond(Calendar calendar) {
  248. Calendar c = (Calendar) calendar.clone();
  249. c.clear();
  250. c.set(Calendar.YEAR, this.year.getYear());
  251. c.set(Calendar.WEEK_OF_YEAR, this.week);
  252. c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek());
  253. c.set(Calendar.HOUR, 0);
  254. c.set(Calendar.MINUTE, 0);
  255. c.set(Calendar.SECOND, 0);
  256. c.set(Calendar.MILLISECOND, 0);
  257. //return c.getTimeInMillis(); // this won't work for JDK 1.3
  258. return c.getTime().getTime();
  259. }
  260. /**
  261. * Returns the last millisecond of the week, evaluated using the supplied
  262. * calendar (which determines the time zone).
  263. *
  264. * @param calendar the calendar.
  265. *
  266. * @return The last millisecond of the week.
  267. */
  268. public long getLastMillisecond(Calendar calendar) {
  269. RegularTimePeriod next = next();
  270. return next.getFirstMillisecond(calendar) - 1;
  271. }
  272. /**
  273. * Returns a string representing the week (e.g. "Week 9, 2002").
  274. *
  275. * TODO: look at internationalisation.
  276. *
  277. * @return A string representing the week.
  278. */
  279. public String toString() {
  280. return "Week " + this.week + ", " + this.year;
  281. }
  282. /**
  283. * Tests the equality of this Week object to an arbitrary object. Returns
  284. * true if the target is a Week instance representing the same week as this
  285. * object. In all other cases, returns false.
  286. * @param obj The object.
  287. *
  288. * @return <code>true</code> if week and year of this and object are the same.
  289. */
  290. public boolean equals(Object obj) {
  291. if (obj == this) {
  292. return true;
  293. }
  294. if (!(obj instanceof Week)) {
  295. return false;
  296. }
  297. Week that = (Week) obj;
  298. if (this.week != that.week) {
  299. return false;
  300. }
  301. if (!this.year.equals(that.year)) {
  302. return false;
  303. }
  304. return true;
  305. }
  306. /**
  307. * Returns a hash code for this object instance.
  308. * <p>
  309. * The approach described by Joshua Bloch in "Effective Java" has been used here:
  310. * <p>
  311. * <code>http://developer.java.sun.com/developer/Books/effectivejava/Chapter3.pdf</code>
  312. *
  313. * @return A hash code.
  314. */
  315. public int hashCode() {
  316. int result = 17;
  317. result = 37 * result + this.week;
  318. result = 37 * result + this.year.hashCode();
  319. return result;
  320. }
  321. /**
  322. * Returns an integer indicating the order of this Week object relative to
  323. * the specified object:
  324. *
  325. * negative == before, zero == same, positive == after.
  326. *
  327. * @param o1 the object to compare.
  328. *
  329. * @return negative == before, zero == same, positive == after.
  330. */
  331. public int compareTo(Object o1) {
  332. int result;
  333. // CASE 1 : Comparing to another Week object
  334. // --------------------------------------------
  335. if (o1 instanceof Week) {
  336. Week w = (Week) o1;
  337. result = this.year.getYear() - w.getYear().getYear();
  338. if (result == 0) {
  339. result = this.week - w.getWeek();
  340. }
  341. }
  342. // CASE 2 : Comparing to another TimePeriod object
  343. // -----------------------------------------------
  344. else if (o1 instanceof RegularTimePeriod) {
  345. // more difficult case - evaluate later...
  346. result = 0;
  347. }
  348. // CASE 3 : Comparing to a non-TimePeriod object
  349. // ---------------------------------------------
  350. else {
  351. // consider time periods to be ordered after general objects
  352. result = 1;
  353. }
  354. return result;
  355. }
  356. /**
  357. * Parses the string argument as a week.
  358. * <P>
  359. * This method is required to accept the format "YYYY-Wnn". It will also
  360. * accept "Wnn-YYYY". Anything else, at the moment, is a bonus.
  361. *
  362. * @param s string to parse.
  363. *
  364. * @return <code>null</code> if the string is not parseable, the week otherwise.
  365. */
  366. public static Week parseWeek(String s) {
  367. Week result = null;
  368. if (s != null) {
  369. // trim whitespace from either end of the string
  370. s = s.trim();
  371. int i = Week.findSeparator(s);
  372. if (i != -1) {
  373. String s1 = s.substring(0, i).trim();
  374. String s2 = s.substring(i + 1, s.length()).trim();
  375. Year y = Week.evaluateAsYear(s1);
  376. int w;
  377. if (y != null) {
  378. w = Week.stringToWeek(s2);
  379. if (w == -1) {
  380. throw new TimePeriodFormatException(
  381. "Week.parseWeek(String): can't evaluate the week.");
  382. }
  383. result = new Week(w, y);
  384. }
  385. else {
  386. y = Week.evaluateAsYear(s2);
  387. if (y != null) {
  388. w = Week.stringToWeek(s1);
  389. if (w == -1) {
  390. throw new TimePeriodFormatException(
  391. "Week.parseWeek(String): can't evaluate the week.");
  392. }
  393. result = new Week(w, y);
  394. }
  395. else {
  396. throw new TimePeriodFormatException(
  397. "Week.parseWeek(String): can't evaluate the year.");
  398. }
  399. }
  400. }
  401. else {
  402. throw new TimePeriodFormatException(
  403. "Week.parseWeek(String): could not find separator.");
  404. }
  405. }
  406. return result;
  407. }
  408. /**
  409. * Finds the first occurrence of ' ', '-', ',' or '.'
  410. *
  411. * @param s the string to parse.
  412. *
  413. * @return <code>-1</code> if none of the characters was found, the
  414. * index of the first occurrence otherwise.
  415. */
  416. private static int findSeparator(String s) {
  417. int result = s.indexOf('-');
  418. if (result == -1) {
  419. result = s.indexOf(',');
  420. }
  421. if (result == -1) {
  422. result = s.indexOf(' ');
  423. }
  424. if (result == -1) {
  425. result = s.indexOf('.');
  426. }
  427. return result;
  428. }
  429. /**
  430. * Creates a year from a string, or returns null (format exceptions
  431. * suppressed).
  432. *
  433. * @param s string to parse.
  434. *
  435. * @return <code>null</code> if the string is not parseable, the year otherwise.
  436. */
  437. private static Year evaluateAsYear(String s) {
  438. Year result = null;
  439. try {
  440. result = Year.parseYear(s);
  441. }
  442. catch (TimePeriodFormatException e) {
  443. // suppress
  444. }
  445. return result;
  446. }
  447. /**
  448. * Converts a string to a week.
  449. *
  450. * @param s the string to parse.
  451. * @return <code>-1</code> if the string does not contain a week number,
  452. * the number of the week otherwise.
  453. */
  454. private static int stringToWeek(String s) {
  455. int result = -1;
  456. s = s.replace('W', ' ');
  457. s = s.trim();
  458. try {
  459. result = Integer.parseInt(s);
  460. if ((result < 1) || (result > LAST_WEEK_IN_YEAR)) {
  461. result = -1;
  462. }
  463. }
  464. catch (NumberFormatException e) {
  465. // suppress
  466. }
  467. return result;
  468. }
  469. }