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