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 * Day.java
029 * --------
030 * (C) Copyright 2001-2016, by Object Refinery Limited.
031 *
032 * Original Author:  David Gilbert (for Object Refinery Limited);
033 * Contributor(s):   -;
034 *
035 * Changes
036 * -------
037 * 11-Oct-2001 : Version 1 (DG);
038 * 15-Nov-2001 : Updated Javadoc comments (DG);
039 * 04-Dec-2001 : Added static method to parse a string into a Day object (DG);
040 * 19-Dec-2001 : Added new constructor as suggested by Paul English (DG);
041 * 29-Jan-2002 : Changed getDay() method to getSerialDate() (DG);
042 * 26-Feb-2002 : Changed getStart(), getMiddle() and getEnd() methods to
043 *               evaluate with reference to a particular time zone (DG);
044 * 19-Mar-2002 : Changed the API for the TimePeriod classes (DG);
045 * 29-May-2002 : Fixed bug in equals method (DG);
046 * 24-Jun-2002 : Removed unnecessary imports (DG);
047 * 10-Sep-2002 : Added getSerialIndex() method (DG);
048 * 07-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 * 30-Sep-2004 : Replaced getTime().getTime() with getTimeInMillis() (DG);
054 * 04-Nov-2004 : Reverted change of 30-Sep-2004, because it won't work for
055 *               JDK 1.3 (DG);
056 * ------------- JFREECHART 1.0.x ---------------------------------------------
057 * 05-Oct-2006 : Updated API docs (DG);
058 * 06-Oct-2006 : Refactored to cache first and last millisecond values (DG);
059 * 16-Sep-2008 : Deprecated DEFAULT_TIME_ZONE (DG);
060 * 02-Mar-2009 : Added new constructor with Locale (DG);
061 * 05-Jul-2012 : Replaced getTime().getTime() with getTimeInMillis() (DG);
062 * 03-Jul-2013 : Use ParamChecks (DG);
063 *
064 */
065
066package org.jfree.data.time;
067
068import java.io.Serializable;
069import java.text.DateFormat;
070import java.text.ParseException;
071import java.text.SimpleDateFormat;
072import java.util.Calendar;
073import java.util.Date;
074import java.util.Locale;
075import java.util.TimeZone;
076import org.jfree.chart.date.SerialDate;
077import org.jfree.chart.util.Args;
078
079/**
080 * Represents a single day in the range 1-Jan-1900 to 31-Dec-9999.  This class
081 * is immutable, which is a requirement for all {@link RegularTimePeriod}
082 * subclasses.
083 */
084public class Day extends RegularTimePeriod implements Serializable {
085
086    /** For serialization. */
087    private static final long serialVersionUID = -7082667380758962755L;
088
089    /** A standard date formatter. */
090    protected static final DateFormat DATE_FORMAT
091            = new SimpleDateFormat("yyyy-MM-dd");
092
093    /** A date formatter for the default locale. */
094    protected static final DateFormat DATE_FORMAT_SHORT 
095            = DateFormat.getDateInstance(DateFormat.SHORT);
096
097    /** A date formatter for the default locale. */
098    protected static final DateFormat DATE_FORMAT_MEDIUM 
099            = DateFormat.getDateInstance(DateFormat.MEDIUM);
100
101    /** A date formatter for the default locale. */
102    protected static final DateFormat DATE_FORMAT_LONG 
103            = DateFormat.getDateInstance(DateFormat.LONG);
104
105    /** The day (uses SerialDate for convenience). */
106    private SerialDate serialDate;
107
108    /** The first millisecond. */
109    private long firstMillisecond;
110
111    /** The last millisecond. */
112    private long lastMillisecond;
113
114    /**
115     * Creates a new instance, derived from the system date/time (and assuming
116     * the default timezone).
117     */
118    public Day() {
119        this(new Date());
120    }
121
122    /**
123     * Constructs a new one day time period.
124     *
125     * @param day  the day-of-the-month.
126     * @param month  the month (1 to 12).
127     * @param year  the year (1900 <= year <= 9999).
128     */
129    public Day(int day, int month, int year) {
130        this.serialDate = SerialDate.createInstance(day, month, year);
131        peg(Calendar.getInstance());
132    }
133
134    /**
135     * Constructs a new one day time period.
136     *
137     * @param serialDate  the day ({@code null} not permitted).
138     */
139    public Day(SerialDate serialDate) {
140        Args.nullNotPermitted(serialDate, "serialDate");
141        this.serialDate = serialDate;
142        peg(Calendar.getInstance());
143    }
144
145    /**
146     * Constructs a new instance, based on a particular date/time and the
147     * default time zone.
148     *
149     * @param time  the time ({@code null} not permitted).
150     *
151     * @see #Day(Date, TimeZone, Locale)
152     */
153    public Day(Date time) {
154        // defer argument checking...
155        this(time, TimeZone.getDefault(), Locale.getDefault());
156    }
157
158    /**
159     * Constructs a new instance, based on a particular date/time and time zone.
160     *
161     * @param time  the date/time ({@code null} not permitted).
162     * @param zone  the time zone ({@code null} not permitted).
163     * @param locale  the locale ({@code null} not permitted).
164     */
165    public Day(Date time, TimeZone zone, Locale locale) {
166        Args.nullNotPermitted(time, "time");
167        Args.nullNotPermitted(zone, "zone");
168        Args.nullNotPermitted(locale, "locale");
169        Calendar calendar = Calendar.getInstance(zone, locale);
170        calendar.setTime(time);
171        int d = calendar.get(Calendar.DAY_OF_MONTH);
172        int m = calendar.get(Calendar.MONTH) + 1;
173        int y = calendar.get(Calendar.YEAR);
174        this.serialDate = SerialDate.createInstance(d, m, y);
175        peg(calendar);
176    }
177
178    /**
179     * Returns the day as a {@link SerialDate}.  Note: the reference that is
180     * returned should be an instance of an immutable {@link SerialDate}
181     * (otherwise the caller could use the reference to alter the state of
182     * this {@code Day} instance, and {@code Day} is supposed
183     * to be immutable).
184     *
185     * @return The day as a {@link SerialDate}.
186     */
187    public SerialDate getSerialDate() {
188        return this.serialDate;
189    }
190
191    /**
192     * Returns the year.
193     *
194     * @return The year.
195     */
196    public int getYear() {
197        return this.serialDate.getYYYY();
198    }
199
200    /**
201     * Returns the month.
202     *
203     * @return The month.
204     */
205    public int getMonth() {
206        return this.serialDate.getMonth();
207    }
208
209    /**
210     * Returns the day of the month.
211     *
212     * @return The day of the month.
213     */
214    public int getDayOfMonth() {
215        return this.serialDate.getDayOfMonth();
216    }
217
218    /**
219     * Returns the first millisecond of the day.  This will be determined
220     * relative to the time zone specified in the constructor, or in the
221     * calendar instance passed in the most recent call to the
222     * {@link #peg(Calendar)} method.
223     *
224     * @return The first millisecond of the day.
225     *
226     * @see #getLastMillisecond()
227     */
228    @Override
229    public long getFirstMillisecond() {
230        return this.firstMillisecond;
231    }
232
233    /**
234     * Returns the last millisecond of the day.  This will be
235     * determined relative to the time zone specified in the constructor, or
236     * in the calendar instance passed in the most recent call to the
237     * {@link #peg(Calendar)} method.
238     *
239     * @return The last millisecond of the day.
240     *
241     * @see #getFirstMillisecond()
242     */
243    @Override
244    public long getLastMillisecond() {
245        return this.lastMillisecond;
246    }
247
248    /**
249     * Recalculates the start date/time and end date/time for this time period
250     * relative to the supplied calendar (which incorporates a time zone).
251     *
252     * @param calendar  the calendar ({@code null} not permitted).
253     *
254     * @since 1.0.3
255     */
256    @Override
257    public void peg(Calendar calendar) {
258        this.firstMillisecond = getFirstMillisecond(calendar);
259        this.lastMillisecond = getLastMillisecond(calendar);
260    }
261
262    /**
263     * Returns the day preceding this one.
264     *
265     * @return The day preceding this one.
266     */
267    @Override
268    public RegularTimePeriod previous() {
269        Day result;
270        int serial = this.serialDate.toSerial();
271        if (serial > SerialDate.SERIAL_LOWER_BOUND) {
272            SerialDate yesterday = SerialDate.createInstance(serial - 1);
273            return new Day(yesterday);
274        }
275        else {
276            result = null;
277        }
278        return result;
279    }
280
281    /**
282     * Returns the day following this one, or {@code null} if some limit
283     * has been reached.
284     *
285     * @return The day following this one, or {@code null} if some limit
286     *         has been reached.
287     */
288    @Override
289    public RegularTimePeriod next() {
290        Day result;
291        int serial = this.serialDate.toSerial();
292        if (serial < SerialDate.SERIAL_UPPER_BOUND) {
293            SerialDate tomorrow = SerialDate.createInstance(serial + 1);
294            return new Day(tomorrow);
295        }
296        else {
297            result = null;
298        }
299        return result;
300    }
301
302    /**
303     * Returns a serial index number for the day.
304     *
305     * @return The serial index number.
306     */
307    @Override
308    public long getSerialIndex() {
309        return this.serialDate.toSerial();
310    }
311
312    /**
313     * Returns the first millisecond of the day, evaluated using the supplied
314     * calendar (which determines the time zone).
315     *
316     * @param calendar  calendar to use ({@code null} not permitted).
317     *
318     * @return The start of the day as milliseconds since 01-01-1970.
319     *
320     * @throws NullPointerException if {@code calendar} is
321     *     {@code null}.
322     */
323    @Override
324    public long getFirstMillisecond(Calendar calendar) {
325        int year = this.serialDate.getYYYY();
326        int month = this.serialDate.getMonth();
327        int day = this.serialDate.getDayOfMonth();
328        calendar.clear();
329        calendar.set(year, month - 1, day, 0, 0, 0);
330        calendar.set(Calendar.MILLISECOND, 0);
331        return calendar.getTimeInMillis();
332    }
333
334    /**
335     * Returns the last millisecond of the day, evaluated using the supplied
336     * calendar (which determines the time zone).
337     *
338     * @param calendar  calendar to use ({@code null} not permitted).
339     *
340     * @return The end of the day as milliseconds since 01-01-1970.
341     *
342     * @throws NullPointerException if {@code calendar} is
343     *     {@code null}.
344     */
345    @Override
346    public long getLastMillisecond(Calendar calendar) {
347        int year = this.serialDate.getYYYY();
348        int month = this.serialDate.getMonth();
349        int day = this.serialDate.getDayOfMonth();
350        calendar.clear();
351        calendar.set(year, month - 1, day, 23, 59, 59);
352        calendar.set(Calendar.MILLISECOND, 999);
353        return calendar.getTimeInMillis();
354    }
355
356    /**
357     * Tests the equality of this Day object to an arbitrary object.  Returns
358     * true if the target is a Day instance or a SerialDate instance
359     * representing the same day as this object. In all other cases,
360     * returns false.
361     *
362     * @param obj  the object ({@code null} permitted).
363     *
364     * @return A flag indicating whether or not an object is equal to this day.
365     */
366    @Override
367    public boolean equals(Object obj) {
368        if (obj == this) {
369            return true;
370        }
371        if (!(obj instanceof Day)) {
372            return false;
373        }
374        Day that = (Day) obj;
375        if (!this.serialDate.equals(that.getSerialDate())) {
376            return false;
377        }
378        return true;
379    }
380
381    /**
382     * Returns a hash code for this object instance.  The approach described by
383     * Joshua Bloch in "Effective Java" has been used here:
384     * <p>
385     * {@code http://developer.java.sun.com/developer/Books/effectivejava
386     * /Chapter3.pdf}
387     *
388     * @return A hash code.
389     */
390    @Override
391    public int hashCode() {
392        return this.serialDate.hashCode();
393    }
394
395    /**
396     * Returns an integer indicating the order of this Day object relative to
397     * the specified object:
398     *
399     * negative == before, zero == same, positive == after.
400     *
401     * @param o1  the object to compare.
402     *
403     * @return negative == before, zero == same, positive == after.
404     */
405    @Override
406    public int compareTo(Object o1) {
407        int result;
408
409        // CASE 1 : Comparing to another Day object
410        // ----------------------------------------
411        if (o1 instanceof Day) {
412            Day d = (Day) o1;
413            result = -d.getSerialDate().compare(this.serialDate);
414        }
415
416        // CASE 2 : Comparing to another TimePeriod object
417        // -----------------------------------------------
418        else if (o1 instanceof RegularTimePeriod) {
419            // more difficult case - evaluate later...
420            result = 0;
421        }
422
423        // CASE 3 : Comparing to a non-TimePeriod object
424        // ---------------------------------------------
425        else {
426            // consider time periods to be ordered after general objects
427            result = 1;
428        }
429
430        return result;
431    }
432
433    /**
434     * Returns a string representing the day.
435     *
436     * @return A string representing the day.
437     */
438    @Override
439    public String toString() {
440        return this.serialDate.toString();
441    }
442
443    /**
444     * Parses the string argument as a day.
445     * <P>
446     * This method is required to recognise YYYY-MM-DD as a valid format.
447     * Anything else, for now, is a bonus.
448     *
449     * @param s  the date string to parse.
450     *
451     * @return {@code null} if the string does not contain any parseable
452     *      string, the day otherwise.
453     */
454    public static Day parseDay(String s) {
455        try {
456            return new Day (Day.DATE_FORMAT.parse(s));
457        }
458        catch (ParseException e1) {
459            try {
460                return new Day (Day.DATE_FORMAT_SHORT.parse(s));
461            }
462            catch (ParseException e2) {
463              // ignore
464            }
465        }
466        return null;
467    }
468
469}