001/* ===========================================================
002 * JFreeChart : a free chart library for the Java(tm) platform
003 * ===========================================================
004 *
005 * (C) Copyright 2000-2017, by Object Refinery Limited 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 * Month.java
029 * ----------
030 * (C) Copyright 2001-2012, by Object Refinery Limited and Contributors.
031 *
032 * Original Author:  David Gilbert (for Object Refinery Limited);
033 * Contributor(s):   Chris Boek;
034 *
035 * Changes
036 * -------
037 * 11-Oct-2001 : Version 1 (DG);
038 * 14-Nov-2001 : Added method to get year as primitive (DG);
039 *               Override for toString() method (DG);
040 * 18-Dec-2001 : Changed order of parameters in constructor (DG);
041 * 19-Dec-2001 : Added a new constructor as suggested by Paul English (DG);
042 * 29-Jan-2002 : Worked on the parseMonth() method (DG);
043 * 14-Feb-2002 : Fixed bugs in the Month constructors (DG);
044 * 26-Feb-2002 : Changed getStart(), getMiddle() and getEnd() methods to
045 *               evaluate with reference to a particular time zone (DG);
046 * 19-Mar-2002 : Changed API for TimePeriod classes (DG);
047 * 10-Sep-2002 : Added getSerialIndex() method (DG);
048 * 04-Oct-2002 : Fixed errors reported by Checkstyle (DG);
049 * 10-Jan-2003 : Changed base class and method names (DG);
050 * 13-Mar-2003 : Moved to com.jrefinery.data.time package, and implemented
051 *               Serializable (DG);
052 * 21-Oct-2003 : Added hashCode() method (DG);
053 * 01-Nov-2005 : Fixed bug 1345383 (argument check in constructor) (DG);
054 * ------------- JFREECHART 1.0.x ---------------------------------------------
055 * 05-Oct-2006 : Updated API docs (DG);
056 * 06-Oct-2006 : Refactored to cache first and last millisecond values (DG);
057 * 04-Apr-2007 : Fixed bug in Month(Date, TimeZone) constructor (CB);
058 * 01-Sep-2008 : Added clarification for previous() and next() methods (DG);
059 * 16-Sep-2008 : Deprecated DEFAULT_TIME_ZONE, and updated parsing to handle
060 *               extended range in Year (DG);
061 * 25-Nov-2008 : Added new constructor with Locale (DG);
062 * 04-Feb-2009 : Fix for new constructor with Locale - bug 2564636 (DG);
063 * 05-Jul-2012 : Removed JDK 1.3.1 supporting code (DG);
064 *
065 */
066
067package org.jfree.data.time;
068
069import java.io.Serializable;
070import java.util.Calendar;
071import java.util.Date;
072import java.util.Locale;
073import java.util.TimeZone;
074import org.jfree.chart.date.MonthConstants;
075import org.jfree.chart.date.SerialDate;
076
077/**
078 * Represents a single month.  This class is immutable, which is a requirement
079 * for all {@link RegularTimePeriod} subclasses.
080 */
081public class Month extends RegularTimePeriod implements Serializable {
082
083    /** For serialization. */
084    private static final long serialVersionUID = -5090216912548722570L;
085
086    /** The month (1-12). */
087    private int month;
088
089    /** The year in which the month falls. */
090    private int year;
091
092    /** The first millisecond. */
093    private long firstMillisecond;
094
095    /** The last millisecond. */
096    private long lastMillisecond;
097
098    /**
099     * Constructs a new Month, based on the current system time.
100     */
101    public Month() {
102        this(new Date());
103    }
104
105    /**
106     * Constructs a new month instance.
107     *
108     * @param month  the month (in the range 1 to 12).
109     * @param year  the year.
110     */
111    public Month(int month, int year) {
112        if ((month < 1) || (month > 12)) {
113            throw new IllegalArgumentException("Month outside valid range.");
114        }
115        this.month = month;
116        this.year = year;
117        peg(Calendar.getInstance());
118    }
119
120    /**
121     * Constructs a new month instance.
122     *
123     * @param month  the month (in the range 1 to 12).
124     * @param year  the year.
125     */
126    public Month(int month, Year year) {
127        if ((month < 1) || (month > 12)) {
128            throw new IllegalArgumentException("Month outside valid range.");
129        }
130        this.month = month;
131        this.year = year.getYear();
132        peg(Calendar.getInstance());
133    }
134
135    /**
136     * Constructs a new {@code Month} instance, based on a date/time and
137     * the default time zone.
138     *
139     * @param time  the date/time ({@code null} not permitted).
140     *
141     * @see #Month(Date, TimeZone, Locale)
142     */
143    public Month(Date time) {
144        this(time, TimeZone.getDefault(), Locale.getDefault());
145    }
146
147    /**
148     * Creates a new {@code Month} instance, based on the specified time,
149     * zone and locale.
150     *
151     * @param time  the current time.
152     * @param zone  the time zone.
153     * @param locale  the locale.
154     *
155     * @since 1.0.12
156     */
157    public Month(Date time, TimeZone zone, Locale locale) {
158        Calendar calendar = Calendar.getInstance(zone, locale);
159        calendar.setTime(time);
160        this.month = calendar.get(Calendar.MONTH) + 1;
161        this.year = calendar.get(Calendar.YEAR);
162        peg(calendar);
163    }
164
165    /**
166     * Returns the year in which the month falls.
167     *
168     * @return The year in which the month falls (as a Year object).
169     */
170    public Year getYear() {
171        return new Year(this.year);
172    }
173
174    /**
175     * Returns the year in which the month falls.
176     *
177     * @return The year in which the month falls (as an int).
178     */
179    public int getYearValue() {
180        return this.year;
181    }
182
183    /**
184     * Returns the month.  Note that 1=JAN, 2=FEB, ...
185     *
186     * @return The month.
187     */
188    public int getMonth() {
189        return this.month;
190    }
191
192    /**
193     * Returns the first millisecond of the month.  This will be determined
194     * relative to the time zone specified in the constructor, or in the
195     * calendar instance passed in the most recent call to the
196     * {@link #peg(Calendar)} method.
197     *
198     * @return The first millisecond of the month.
199     *
200     * @see #getLastMillisecond()
201     */
202    @Override
203    public long getFirstMillisecond() {
204        return this.firstMillisecond;
205    }
206
207    /**
208     * Returns the last millisecond of the month.  This will be
209     * determined relative to the time zone specified in the constructor, or
210     * in the calendar instance passed in the most recent call to the
211     * {@link #peg(Calendar)} method.
212     *
213     * @return The last millisecond of the month.
214     *
215     * @see #getFirstMillisecond()
216     */
217    @Override
218    public long getLastMillisecond() {
219        return this.lastMillisecond;
220    }
221
222    /**
223     * Recalculates the start date/time and end date/time for this time period
224     * relative to the supplied calendar (which incorporates a time zone).
225     *
226     * @param calendar  the calendar ({@code null} not permitted).
227     *
228     * @since 1.0.3
229     */
230    @Override
231    public void peg(Calendar calendar) {
232        this.firstMillisecond = getFirstMillisecond(calendar);
233        this.lastMillisecond = getLastMillisecond(calendar);
234    }
235
236    /**
237     * Returns the month preceding this one.  Note that the returned
238     * {@link Month} is "pegged" using the default time-zone, irrespective of
239     * the time-zone used to peg of the current month (which is not recorded
240     * anywhere).  See the {@link #peg(Calendar)} method.
241     *
242     * @return The month preceding this one.
243     */
244    @Override
245    public RegularTimePeriod previous() {
246        Month result;
247        if (this.month != MonthConstants.JANUARY) {
248            result = new Month(this.month - 1, this.year);
249        }
250        else {
251            if (this.year > 1900) {
252                result = new Month(MonthConstants.DECEMBER, this.year - 1);
253            }
254            else {
255                result = null;
256            }
257        }
258        return result;
259    }
260
261    /**
262     * Returns the month following this one.  Note that the returned
263     * {@link Month} is "pegged" using the default time-zone, irrespective of
264     * the time-zone used to peg of the current month (which is not recorded
265     * anywhere).  See the {@link #peg(Calendar)} method.
266     *
267     * @return The month following this one.
268     */
269    @Override
270    public RegularTimePeriod next() {
271        Month result;
272        if (this.month != MonthConstants.DECEMBER) {
273            result = new Month(this.month + 1, this.year);
274        }
275        else {
276            if (this.year < 9999) {
277                result = new Month(MonthConstants.JANUARY, this.year + 1);
278            }
279            else {
280                result = null;
281            }
282        }
283        return result;
284    }
285
286    /**
287     * Returns a serial index number for the month.
288     *
289     * @return The serial index number.
290     */
291    @Override
292    public long getSerialIndex() {
293        return this.year * 12L + this.month;
294    }
295
296    /**
297     * Returns a string representing the month (e.g. "January 2002").
298     * <P>
299     * To do: look at internationalisation.
300     *
301     * @return A string representing the month.
302     */
303    @Override
304    public String toString() {
305        return SerialDate.monthCodeToString(this.month) + " " + this.year;
306    }
307
308    /**
309     * Tests the equality of this Month object to an arbitrary object.
310     * Returns true if the target is a Month instance representing the same
311     * month as this object.  In all other cases, returns false.
312     *
313     * @param obj  the object ({@code null} permitted).
314     *
315     * @return {@code true} if month and year of this and object are the
316     *         same.
317     */
318    @Override
319    public boolean equals(Object obj) {
320        if (obj == this) {
321            return true;
322        }
323        if (!(obj instanceof Month)) {
324            return false;
325        }
326        Month that = (Month) obj;
327        if (this.month != that.month) {
328            return false;
329        }
330        if (this.year != that.year) {
331            return false;
332        }
333        return true;
334    }
335
336    /**
337     * Returns a hash code for this object instance.  The approach described by
338     * Joshua Bloch in "Effective Java" has been used here:
339     * <p>
340     * {@code http://developer.java.sun.com/developer/Books/effectivejava
341     * /Chapter3.pdf}
342     *
343     * @return A hash code.
344     */
345    @Override
346    public int hashCode() {
347        int result = 17;
348        result = 37 * result + this.month;
349        result = 37 * result + this.year;
350        return result;
351    }
352
353    /**
354     * Returns an integer indicating the order of this Month object relative to
355     * the specified
356     * object: negative == before, zero == same, positive == after.
357     *
358     * @param o1  the object to compare.
359     *
360     * @return negative == before, zero == same, positive == after.
361     */
362    @Override
363    public int compareTo(Object o1) {
364
365        int result;
366
367        // CASE 1 : Comparing to another Month object
368        // --------------------------------------------
369        if (o1 instanceof Month) {
370            Month m = (Month) o1;
371            result = this.year - m.getYearValue();
372            if (result == 0) {
373                result = this.month - m.getMonth();
374            }
375        }
376
377        // CASE 2 : Comparing to another TimePeriod object
378        // -----------------------------------------------
379        else if (o1 instanceof RegularTimePeriod) {
380            // more difficult case - evaluate later...
381            result = 0;
382        }
383
384        // CASE 3 : Comparing to a non-TimePeriod object
385        // ---------------------------------------------
386        else {
387            // consider time periods to be ordered after general objects
388            result = 1;
389        }
390
391        return result;
392
393    }
394
395    /**
396     * Returns the first millisecond of the month, evaluated using the supplied
397     * calendar (which determines the time zone).
398     *
399     * @param calendar  the calendar ({@code null} not permitted).
400     *
401     * @return The first millisecond of the month.
402     *
403     * @throws NullPointerException if {@code calendar} is
404     *     {@code null}.
405     */
406    @Override
407    public long getFirstMillisecond(Calendar calendar) {
408        calendar.set(this.year, this.month - 1, 1, 0, 0, 0);
409        calendar.set(Calendar.MILLISECOND, 0);
410        return calendar.getTimeInMillis();
411    }
412
413    /**
414     * Returns the last millisecond of the month, evaluated using the supplied
415     * calendar (which determines the time zone).
416     *
417     * @param calendar  the calendar ({@code null} not permitted).
418     *
419     * @return The last millisecond of the month.
420     *
421     * @throws NullPointerException if {@code calendar} is
422     *     {@code null}.
423     */
424    @Override
425    public long getLastMillisecond(Calendar calendar) {
426        int eom = SerialDate.lastDayOfMonth(this.month, this.year);
427        calendar.set(this.year, this.month - 1, eom, 23, 59, 59);
428        calendar.set(Calendar.MILLISECOND, 999);
429        return calendar.getTimeInMillis();
430    }
431
432    /**
433     * Parses the string argument as a month.  This method is required to
434     * accept the format "YYYY-MM".  It will also accept "MM-YYYY". Anything
435     * else, at the moment, is a bonus.
436     *
437     * @param s  the string to parse ({@code null} permitted).
438     *
439     * @return {@code null} if the string is not parseable, the month
440     *         otherwise.
441     */
442    public static Month parseMonth(String s) {
443        Month result = null;
444        if (s == null) {
445            return result;
446        }
447        // trim whitespace from either end of the string
448        s = s.trim();
449        int i = Month.findSeparator(s);
450        String s1, s2;
451        boolean yearIsFirst;
452        // if there is no separator, we assume the first four characters
453        // are YYYY
454        if (i == -1) {
455            yearIsFirst = true;
456            s1 = s.substring(0, 5);
457            s2 = s.substring(5);
458        }
459        else {
460            s1 = s.substring(0, i).trim();
461            s2 = s.substring(i + 1, s.length()).trim();
462            // now it is trickier to determine if the month or year is first
463            Year y1 = Month.evaluateAsYear(s1);
464            if (y1 == null) {
465                yearIsFirst = false;
466            }
467            else {
468                Year y2 = Month.evaluateAsYear(s2);
469                if (y2 == null) {
470                    yearIsFirst = true;
471                }
472                else {
473                    yearIsFirst = (s1.length() > s2.length());
474                }
475            }
476        }
477        Year year;
478        int month;
479        if (yearIsFirst) {
480            year = Month.evaluateAsYear(s1);
481            month = SerialDate.stringToMonthCode(s2);
482        }
483        else {
484            year = Month.evaluateAsYear(s2);
485            month = SerialDate.stringToMonthCode(s1);
486        }
487        if (month == -1) {
488            throw new TimePeriodFormatException("Can't evaluate the month.");
489        }
490        if (year == null) {
491            throw new TimePeriodFormatException("Can't evaluate the year.");
492        }
493        result = new Month(month, year);
494        return result;
495    }
496
497    /**
498     * Finds the first occurrence of '-', or if that character is not found,
499     * the first occurrence of ',', or the first occurrence of ' ' or '.'
500     *
501     * @param s  the string to parse.
502     *
503     * @return The position of the separator character, or {@code -1} if
504     *     none of the characters were found.
505     */
506    private static int findSeparator(String s) {
507        int result = s.indexOf('-');
508        if (result == -1) {
509            result = s.indexOf(',');
510        }
511        if (result == -1) {
512            result = s.indexOf(' ');
513        }
514        if (result == -1) {
515            result = s.indexOf('.');
516        }
517        return result;
518    }
519
520    /**
521     * Creates a year from a string, or returns {@code null} (format
522     * exceptions suppressed).
523     *
524     * @param s  the string to parse.
525     *
526     * @return {@code null} if the string is not parseable, the year
527     *         otherwise.
528     */
529    private static Year evaluateAsYear(String s) {
530        Year result = null;
531        try {
532            result = Year.parseYear(s);
533        }
534        catch (TimePeriodFormatException e) {
535            // suppress
536        }
537        return result;
538    }
539
540}