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