001/* ===========================================================
002 * JFreeChart : a free chart library for the Java(tm) platform
003 * ===========================================================
004 *
005 * (C) Copyright 2000-2022, by David Gilbert and Contributors.
006 *
007 * Project Info:  http://www.jfree.org/jfreechart/index.html
008 *
009 * This library is free software; you can redistribute it and/or modify it
010 * under the terms of the GNU Lesser General Public License as published by
011 * the Free Software Foundation; either version 2.1 of the License, or
012 * (at your option) any later version.
013 *
014 * This library is distributed in the hope that it will be useful, but
015 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
016 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
017 * License for more details.
018 *
019 * You should have received a copy of the GNU Lesser General Public
020 * License along with this library; if not, write to the Free Software
021 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
022 * USA.
023 *
024 * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. 
025 * Other names may be trademarks of their respective owners.]
026 *
027 * ---------
028 * Year.java
029 * ---------
030 * (C) Copyright 2001-2022, by David Gilbert.
031 *
032 * Original Author:  David Gilbert;
033 * Contributor(s):   -;
034 *
035 */
036
037package org.jfree.data.time;
038
039import java.io.Serializable;
040import java.util.Calendar;
041import java.util.Date;
042import java.util.Locale;
043import java.util.TimeZone;
044
045/**
046 * Represents a year in the range -9999 to 9999.  This class is immutable,
047 * which is a requirement for all {@link RegularTimePeriod} subclasses.
048 */
049public class Year extends RegularTimePeriod implements Serializable {
050
051    /**
052     * The minimum year value.
053     *
054     * @since 1.0.11
055     */
056    public static final int MINIMUM_YEAR = -9999;
057
058    /**
059     * The maximum year value.
060     *
061     * @since 1.0.11
062     */
063    public static final int MAXIMUM_YEAR = 9999;
064
065    /** For serialization. */
066    private static final long serialVersionUID = -7659990929736074836L;
067
068    /** The year. */
069    private short year;
070
071    /** The first millisecond. */
072    private long firstMillisecond;
073
074    /** The last millisecond. */
075    private long lastMillisecond;
076
077    /**
078     * Creates a new {@code Year}, based on the current system date/time.
079     * The time zone and locale are determined by the calendar
080     * returned by {@link RegularTimePeriod#getCalendarInstance()}.
081     */
082    public Year() {
083        this(new Date());
084    }
085
086    /**
087     * Creates a time period representing a single year.
088     * The time zone and locale are determined by the calendar
089     * returned by {@link RegularTimePeriod#getCalendarInstance()}.
090     *
091     * @param year  the year.
092     */
093    public Year(int year) {
094        if ((year < Year.MINIMUM_YEAR) || (year > Year.MAXIMUM_YEAR)) {
095            throw new IllegalArgumentException(
096                "Year constructor: year (" + year + ") outside valid range.");
097        }
098        this.year = (short) year;
099        peg(getCalendarInstance());
100    }
101
102    /**
103     * Creates a new {@code Year}, based on a particular instant in time.
104     * The time zone and locale are determined by the calendar
105     * returned by {@link RegularTimePeriod#getCalendarInstance()}.
106     *
107     * @param time  the time ({@code null} not permitted).
108     *
109     * @see #Year(Date, TimeZone, Locale)
110     */
111    public Year(Date time) {
112        this(time, getCalendarInstance());
113    }
114
115    /**
116     * Creates a new {@code Year} instance, for the specified time zone
117     * and locale.
118     *
119     * @param time  the current time ({@code null} not permitted).
120     * @param zone  the time zone.
121     * @param locale  the locale.
122     *
123     * @since 1.0.12
124     */
125    public Year(Date time, TimeZone zone, Locale locale) {
126        Calendar calendar = Calendar.getInstance(zone, locale);
127        calendar.setTime(time);
128        this.year = (short) calendar.get(Calendar.YEAR);
129        peg(calendar);
130    }
131
132    /**
133     * Constructs a new instance, based on a particular date/time.
134     * The time zone and locale are determined by the {@code calendar}
135     * parameter.
136     *
137     * @param time the date/time ({@code null} not permitted).
138     * @param calendar the calendar to use for calculations ({@code null} not permitted).
139     */
140    public Year(Date time, Calendar calendar) {
141        calendar.setTime(time);
142        this.year = (short) calendar.get(Calendar.YEAR);
143        peg(calendar);
144    }
145
146    /**
147     * Returns the year.
148     *
149     * @return The year.
150     */
151    public int getYear() {
152        return this.year;
153    }
154
155    /**
156     * Returns the first millisecond of the year.  This will be determined
157     * relative to the time zone specified in the constructor, or in the
158     * calendar instance passed in the most recent call to the
159     * {@link #peg(Calendar)} method.
160     *
161     * @return The first millisecond of the year.
162     *
163     * @see #getLastMillisecond()
164     */
165    @Override
166    public long getFirstMillisecond() {
167        return this.firstMillisecond;
168    }
169
170    /**
171     * Returns the last millisecond of the year.  This will be
172     * determined relative to the time zone specified in the constructor, or
173     * in the calendar instance passed in the most recent call to the
174     * {@link #peg(Calendar)} method.
175     *
176     * @return The last millisecond of the year.
177     *
178     * @see #getFirstMillisecond()
179     */
180    @Override
181    public long getLastMillisecond() {
182        return this.lastMillisecond;
183    }
184
185    /**
186     * Recalculates the start date/time and end date/time for this time period
187     * relative to the supplied calendar (which incorporates a time zone).
188     *
189     * @param calendar  the calendar ({@code null} not permitted).
190     *
191     * @since 1.0.3
192     */
193    @Override
194    public void peg(Calendar calendar) {
195        this.firstMillisecond = getFirstMillisecond(calendar);
196        this.lastMillisecond = getLastMillisecond(calendar);
197    }
198
199    /**
200     * Returns the year preceding this one.
201     * No matter what time zone and locale this instance was created with,
202     * the returned instance will use the default calendar for time
203     * calculations, obtained with {@link RegularTimePeriod#getCalendarInstance()}.
204     *
205     * @return The year preceding this one (or {@code null} if the
206     *         current year is -9999).
207     */
208    @Override
209    public RegularTimePeriod previous() {
210        if (this.year > Year.MINIMUM_YEAR) {
211            return new Year(this.year - 1);
212        }
213        else {
214            return null;
215        }
216    }
217
218    /**
219     * Returns the year following this one.
220     * No matter what time zone and locale this instance was created with,
221     * the returned instance will use the default calendar for time
222     * calculations, obtained with {@link RegularTimePeriod#getCalendarInstance()}.
223     *
224     * @return The year following this one (or {@code null} if the current
225     *         year is 9999).
226     */
227    @Override
228    public RegularTimePeriod next() {
229        if (this.year < Year.MAXIMUM_YEAR) {
230            return new Year(this.year + 1);
231        }
232        else {
233            return null;
234        }
235    }
236
237    /**
238     * Returns a serial index number for the year.
239     * <P>
240     * The implementation simply returns the year number (e.g. 2002).
241     *
242     * @return The serial index number.
243     */
244    @Override
245    public long getSerialIndex() {
246        return this.year;
247    }
248
249    /**
250     * Returns the first millisecond of the year, evaluated using the supplied
251     * calendar (which determines the time zone).
252     *
253     * @param calendar  the calendar ({@code null} not permitted).
254     *
255     * @return The first millisecond of the year.
256     *
257     * @throws NullPointerException if {@code calendar} is
258     *     {@code null}.
259     */
260    @Override
261    public long getFirstMillisecond(Calendar calendar) {
262        calendar.set(this.year, Calendar.JANUARY, 1, 0, 0, 0);
263        calendar.set(Calendar.MILLISECOND, 0);
264        return calendar.getTimeInMillis();
265    }
266
267    /**
268     * Returns the last millisecond of the year, evaluated using the supplied
269     * calendar (which determines the time zone).
270     *
271     * @param calendar  the calendar ({@code null} not permitted).
272     *
273     * @return The last millisecond of the year.
274     *
275     * @throws NullPointerException if {@code calendar} is
276     *     {@code null}.
277     */
278    @Override
279    public long getLastMillisecond(Calendar calendar) {
280        calendar.set(this.year, Calendar.DECEMBER, 31, 23, 59, 59);
281        calendar.set(Calendar.MILLISECOND, 999);
282        return calendar.getTimeInMillis();
283    }
284
285    /**
286     * Tests the equality of this {@code Year} object to an arbitrary
287     * object.  Returns {@code true} if the target is a {@code Year}
288     * instance representing the same year as this object.  In all other cases,
289     * returns {@code false}.
290     *
291     * @param obj  the object ({@code null} permitted).
292     *
293     * @return {@code true} if the year of this and the object are the
294     *         same.
295     */
296    @Override
297    public boolean equals(Object obj) {
298        if (obj == this) {
299            return true;
300        }
301        if (!(obj instanceof Year)) {
302            return false;
303        }
304        Year that = (Year) obj;
305        return (this.year == that.year);
306    }
307
308    /**
309     * Returns a hash code for this object instance.  The approach described by
310     * Joshua Bloch in "Effective Java" has been used here:
311     * <p>
312     * {@code http://developer.java.sun.com/developer/Books/effectivejava
313     *     /Chapter3.pdf}
314     *
315     * @return A hash code.
316     */
317    @Override
318    public int hashCode() {
319        int result = 17;
320        int c = this.year;
321        result = 37 * result + c;
322        return result;
323    }
324
325    /**
326     * Returns an integer indicating the order of this {@code Year} object
327     * relative to the specified object:
328     *
329     * negative == before, zero == same, positive == after.
330     *
331     * @param o1  the object to compare.
332     *
333     * @return negative == before, zero == same, positive == after.
334     */
335    @Override
336    public int compareTo(Object o1) {
337
338        int result;
339
340        // CASE 1 : Comparing to another Year object
341        // -----------------------------------------
342        if (o1 instanceof Year) {
343            Year y = (Year) o1;
344            result = this.year - y.getYear();
345        }
346
347        // CASE 2 : Comparing to another TimePeriod object
348        // -----------------------------------------------
349        else if (o1 instanceof RegularTimePeriod) {
350            // more difficult case - evaluate later...
351            result = 0;
352        }
353
354        // CASE 3 : Comparing to a non-TimePeriod object
355        // ---------------------------------------------
356        else {
357            // consider time periods to be ordered after general objects
358            result = 1;
359        }
360
361        return result;
362
363    }
364
365    /**
366     * Returns a string representing the year..
367     *
368     * @return A string representing the year.
369     */
370    @Override
371    public String toString() {
372        return Integer.toString(this.year);
373    }
374
375    /**
376     * Parses the string argument as a year.
377     * <P>
378     * The string format is YYYY.
379     *
380     * @param s  a string representing the year.
381     *
382     * @return {@code null} if the string is not parseable, the year
383     *         otherwise.
384     */
385    public static Year parseYear(String s) {
386
387        // parse the string...
388        int y;
389        try {
390            y = Integer.parseInt(s.trim());
391        }
392        catch (NumberFormatException e) {
393            throw new TimePeriodFormatException("Cannot parse string.");
394        }
395
396        // create the year...
397        try {
398            return new Year(y);
399        }
400        catch (IllegalArgumentException e) {
401            throw new TimePeriodFormatException("Year outside valid range.");
402        }
403    }
404
405}