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 * RelativeDateFormat.java
029 * -----------------------
030 * (C) Copyright 2006-2016, by Object Refinery Limited and Contributors.
031 *
032 * Original Author:  David Gilbert (for Object Refinery Limited);
033 * Contributor(s):   Michael Siemer;
034 *
035 * Changes:
036 * --------
037 * 01-Nov-2006 : Version 1 (DG);
038 * 23-Nov-2006 : Added argument checks, updated equals(), added clone() and
039 *               hashCode() (DG);
040 * 15-Feb-2008 : Applied patch 1873328 by Michael Siemer, with minor
041 *               modifications (DG);
042 * 01-Sep-2008 : Added new fields for hour and minute formatting, based on
043 *               patch 2033092 (DG);
044 * 02-Jul-2013 : Use ParamChecks, and fix NB warnings (DG);
045 *
046 */
047
048package org.jfree.chart.util;
049
050import java.text.DateFormat;
051import java.text.DecimalFormat;
052import java.text.FieldPosition;
053import java.text.NumberFormat;
054import java.text.ParsePosition;
055import java.util.Date;
056import java.util.GregorianCalendar;
057
058/**
059 * A formatter that formats dates to show the elapsed time relative to some
060 * base date.
061 *
062 * @since 1.0.3
063 */
064public class RelativeDateFormat extends DateFormat {
065
066    /** The base milliseconds for the elapsed time calculation. */
067    private long baseMillis;
068
069    /**
070     * A flag that controls whether or not a zero day count is displayed.
071     */
072    private boolean showZeroDays;
073
074    /**
075     * A flag that controls whether or not a zero hour count is displayed.
076     *
077     * @since 1.0.10
078     */
079    private boolean showZeroHours;
080
081    /**
082     * A formatter for the day count (most likely not critical until the
083     * day count exceeds 999).
084     */
085    private NumberFormat dayFormatter;
086
087    /**
088     * A prefix prepended to the start of the format if the relative date is
089     * positive.
090     *
091     * @since 1.0.10
092     */
093    private String positivePrefix;
094
095    /**
096     * A string appended after the day count.
097     */
098    private String daySuffix;
099
100    /**
101     * A formatter for the hours.
102     *
103     * @since 1.0.11
104     */
105    private NumberFormat hourFormatter;
106
107    /**
108     * A string appended after the hours.
109     */
110    private String hourSuffix;
111
112    /**
113     * A formatter for the minutes.
114     *
115     * @since 1.0.11
116     */
117    private NumberFormat minuteFormatter;
118
119    /**
120     * A string appended after the minutes.
121     */
122    private String minuteSuffix;
123
124    /**
125     * A formatter for the seconds (and milliseconds).
126     */
127    private NumberFormat secondFormatter;
128
129    /**
130     * A string appended after the seconds.
131     */
132    private String secondSuffix;
133
134    /**
135     * A constant for the number of milliseconds in one hour.
136     */
137    private static final long MILLISECONDS_IN_ONE_HOUR = 60 * 60 * 1000L;
138
139    /**
140     * A constant for the number of milliseconds in one day.
141     */
142    private static final long MILLISECONDS_IN_ONE_DAY 
143            = 24 * MILLISECONDS_IN_ONE_HOUR;
144
145    /**
146     * Creates a new instance with base milliseconds set to zero.
147     */
148    public RelativeDateFormat() {
149        this(0L);
150    }
151
152    /**
153     * Creates a new instance.
154     *
155     * @param time  the date/time ({@code null} not permitted).
156     */
157    public RelativeDateFormat(Date time) {
158        this(time.getTime());
159    }
160
161    /**
162     * Creates a new instance.
163     *
164     * @param baseMillis  the time zone ({@code null} not permitted).
165     */
166    public RelativeDateFormat(long baseMillis) {
167        super();
168        this.baseMillis = baseMillis;
169        this.showZeroDays = false;
170        this.showZeroHours = true;
171        this.positivePrefix = "";
172        this.dayFormatter = NumberFormat.getNumberInstance();
173        this.daySuffix = "d";
174        this.hourFormatter = NumberFormat.getNumberInstance();
175        this.hourSuffix = "h";
176        this.minuteFormatter = NumberFormat.getNumberInstance();
177        this.minuteSuffix = "m";
178        this.secondFormatter = NumberFormat.getNumberInstance();
179        this.secondFormatter.setMaximumFractionDigits(3);
180        this.secondFormatter.setMinimumFractionDigits(3);
181        this.secondSuffix = "s";
182
183        // we don't use the calendar or numberFormat fields, but equals(Object)
184        // is failing without them being non-null
185        this.calendar = new GregorianCalendar();
186        this.numberFormat = new DecimalFormat("0");
187    }
188
189    /**
190     * Returns the base date/time used to calculate the elapsed time for
191     * display.
192     *
193     * @return The base date/time in milliseconds since 1-Jan-1970.
194     *
195     * @see #setBaseMillis(long)
196     */
197    public long getBaseMillis() {
198        return this.baseMillis;
199    }
200
201    /**
202     * Sets the base date/time used to calculate the elapsed time for display.
203     * This should be specified in milliseconds using the same encoding as
204     * {@code java.util.Date}.
205     *
206     * @param baseMillis  the base date/time in milliseconds.
207     *
208     * @see #getBaseMillis()
209     */
210    public void setBaseMillis(long baseMillis) {
211        this.baseMillis = baseMillis;
212    }
213
214    /**
215     * Returns the flag that controls whether or not zero day counts are
216     * shown in the formatted output.
217     *
218     * @return The flag.
219     *
220     * @see #setShowZeroDays(boolean)
221     */
222    public boolean getShowZeroDays() {
223        return this.showZeroDays;
224    }
225
226    /**
227     * Sets the flag that controls whether or not zero day counts are shown
228     * in the formatted output.
229     *
230     * @param show  the flag.
231     *
232     * @see #getShowZeroDays()
233     */
234    public void setShowZeroDays(boolean show) {
235        this.showZeroDays = show;
236    }
237
238    /**
239     * Returns the flag that controls whether or not zero hour counts are
240     * shown in the formatted output.
241     *
242     * @return The flag.
243     *
244     * @see #setShowZeroHours(boolean)
245     *
246     * @since 1.0.10
247     */
248    public boolean getShowZeroHours() {
249        return this.showZeroHours;
250    }
251
252    /**
253     * Sets the flag that controls whether or not zero hour counts are shown
254     * in the formatted output.
255     *
256     * @param show  the flag.
257     *
258     * @see #getShowZeroHours()
259     *
260     * @since 1.0.10
261     */
262    public void setShowZeroHours(boolean show) {
263        this.showZeroHours = show;
264    }
265
266    /**
267     * Returns the string that is prepended to the format if the relative time
268     * is positive.
269     *
270     * @return The string (never {@code null}).
271     *
272     * @see #setPositivePrefix(String)
273     *
274     * @since 1.0.10
275     */
276    public String getPositivePrefix() {
277        return this.positivePrefix;
278    }
279
280    /**
281     * Sets the string that is prepended to the format if the relative time is
282     * positive.
283     *
284     * @param prefix  the prefix ({@code null} not permitted).
285     *
286     * @see #getPositivePrefix()
287     *
288     * @since 1.0.10
289     */
290    public void setPositivePrefix(String prefix) {
291        Args.nullNotPermitted(prefix, "prefix");
292        this.positivePrefix = prefix;
293    }
294
295    /**
296     * Sets the formatter for the days.
297     *
298     * @param formatter  the formatter ({@code null} not permitted).
299     *
300     * @since 1.0.11
301     */
302    public void setDayFormatter(NumberFormat formatter) {
303        Args.nullNotPermitted(formatter, "formatter");
304        this.dayFormatter = formatter;
305    }
306
307    /**
308     * Returns the string that is appended to the day count.
309     *
310     * @return The string.
311     *
312     * @see #setDaySuffix(String)
313     */
314    public String getDaySuffix() {
315        return this.daySuffix;
316    }
317
318    /**
319     * Sets the string that is appended to the day count.
320     *
321     * @param suffix  the suffix ({@code null} not permitted).
322     *
323     * @see #getDaySuffix()
324     */
325    public void setDaySuffix(String suffix) {
326        Args.nullNotPermitted(suffix, "suffix");
327        this.daySuffix = suffix;
328    }
329
330    /**
331     * Sets the formatter for the hours.
332     *
333     * @param formatter  the formatter ({@code null} not permitted).
334     *
335     * @since 1.0.11
336     */
337    public void setHourFormatter(NumberFormat formatter) {
338        Args.nullNotPermitted(formatter, "formatter");
339        this.hourFormatter = formatter;
340    }
341
342    /**
343     * Returns the string that is appended to the hour count.
344     *
345     * @return The string.
346     *
347     * @see #setHourSuffix(String)
348     */
349    public String getHourSuffix() {
350        return this.hourSuffix;
351    }
352
353    /**
354     * Sets the string that is appended to the hour count.
355     *
356     * @param suffix  the suffix ({@code null} not permitted).
357     *
358     * @see #getHourSuffix()
359     */
360    public void setHourSuffix(String suffix) {
361        Args.nullNotPermitted(suffix, "suffix");
362        this.hourSuffix = suffix;
363    }
364
365    /**
366     * Sets the formatter for the minutes.
367     *
368     * @param formatter  the formatter ({@code null} not permitted).
369     *
370     * @since 1.0.11
371     */
372    public void setMinuteFormatter(NumberFormat formatter) {
373        Args.nullNotPermitted(formatter, "formatter");
374        this.minuteFormatter = formatter;
375    }
376
377    /**
378     * Returns the string that is appended to the minute count.
379     *
380     * @return The string.
381     *
382     * @see #setMinuteSuffix(String)
383     */
384    public String getMinuteSuffix() {
385        return this.minuteSuffix;
386    }
387
388    /**
389     * Sets the string that is appended to the minute count.
390     *
391     * @param suffix  the suffix ({@code null} not permitted).
392     *
393     * @see #getMinuteSuffix()
394     */
395    public void setMinuteSuffix(String suffix) {
396        Args.nullNotPermitted(suffix, "suffix");
397        this.minuteSuffix = suffix;
398    }
399
400    /**
401     * Returns the string that is appended to the second count.
402     *
403     * @return The string.
404     *
405     * @see #setSecondSuffix(String)
406     */
407    public String getSecondSuffix() {
408        return this.secondSuffix;
409    }
410
411    /**
412     * Sets the string that is appended to the second count.
413     *
414     * @param suffix  the suffix ({@code null} not permitted).
415     *
416     * @see #getSecondSuffix()
417     */
418    public void setSecondSuffix(String suffix) {
419        Args.nullNotPermitted(suffix, "suffix");
420        this.secondSuffix = suffix;
421    }
422
423    /**
424     * Sets the formatter for the seconds and milliseconds.
425     *
426     * @param formatter  the formatter ({@code null} not permitted).
427     */
428    public void setSecondFormatter(NumberFormat formatter) {
429        Args.nullNotPermitted(formatter, "formatter");
430        this.secondFormatter = formatter;
431    }
432
433    /**
434     * Formats the given date as the amount of elapsed time (relative to the
435     * base date specified in the constructor).
436     *
437     * @param date  the date.
438     * @param toAppendTo  the string buffer.
439     * @param fieldPosition  the field position.
440     *
441     * @return The formatted date.
442     */
443    @Override
444    public StringBuffer format(Date date, StringBuffer toAppendTo,
445                               FieldPosition fieldPosition) {
446        long currentMillis = date.getTime();
447        long elapsed = currentMillis - this.baseMillis;
448        String signPrefix;
449        if (elapsed < 0) {
450            elapsed *= -1L;
451            signPrefix = "-";
452        }
453        else {
454            signPrefix = this.positivePrefix;
455        }
456
457        long days = elapsed / MILLISECONDS_IN_ONE_DAY;
458        elapsed = elapsed - (days * MILLISECONDS_IN_ONE_DAY);
459        long hours = elapsed / MILLISECONDS_IN_ONE_HOUR;
460        elapsed = elapsed - (hours * MILLISECONDS_IN_ONE_HOUR);
461        long minutes = elapsed / 60000L;
462        elapsed = elapsed - (minutes * 60000L);
463        double seconds = elapsed / 1000.0;
464
465        toAppendTo.append(signPrefix);
466        if (days != 0 || this.showZeroDays) {
467            toAppendTo.append(this.dayFormatter.format(days))
468                    .append(getDaySuffix());
469        }
470        if (hours != 0 || this.showZeroHours) {
471            toAppendTo.append(this.hourFormatter.format(hours))
472                    .append(getHourSuffix());
473        }
474        toAppendTo.append(this.minuteFormatter.format(minutes))
475                .append(getMinuteSuffix());
476        toAppendTo.append(this.secondFormatter.format(seconds))
477                .append(getSecondSuffix());
478        return toAppendTo;
479    }
480
481    /**
482     * Parses the given string (not implemented).
483     *
484     * @param source  the date string.
485     * @param pos  the parse position.
486     *
487     * @return {@code null}, as this method has not been implemented.
488     */
489    @Override
490    public Date parse(String source, ParsePosition pos) {
491        return null;
492    }
493
494    /**
495     * Tests this formatter for equality with an arbitrary object.
496     *
497     * @param obj  the object ({@code null} permitted).
498     *
499     * @return A boolean.
500     */
501    @Override
502    public boolean equals(Object obj) {
503        if (obj == this) {
504            return true;
505        }
506        if (!(obj instanceof RelativeDateFormat)) {
507            return false;
508        }
509        if (!super.equals(obj)) {
510            return false;
511        }
512        RelativeDateFormat that = (RelativeDateFormat) obj;
513        if (this.baseMillis != that.baseMillis) {
514            return false;
515        }
516        if (this.showZeroDays != that.showZeroDays) {
517            return false;
518        }
519        if (this.showZeroHours != that.showZeroHours) {
520            return false;
521        }
522        if (!this.positivePrefix.equals(that.positivePrefix)) {
523            return false;
524        }
525        if (!this.daySuffix.equals(that.daySuffix)) {
526            return false;
527        }
528        if (!this.hourSuffix.equals(that.hourSuffix)) {
529            return false;
530        }
531        if (!this.minuteSuffix.equals(that.minuteSuffix)) {
532            return false;
533        }
534        if (!this.secondSuffix.equals(that.secondSuffix)) {
535            return false;
536        }
537        if (!this.dayFormatter.equals(that.dayFormatter)) {
538            return false;
539        }
540        if (!this.hourFormatter.equals(that.hourFormatter)) {
541            return false;
542        }
543        if (!this.minuteFormatter.equals(that.minuteFormatter)) {
544            return false;
545        }
546        if (!this.secondFormatter.equals(that.secondFormatter)) {
547            return false;
548        }
549        return true;
550    }
551
552    /**
553     * Returns a hash code for this instance.
554     *
555     * @return A hash code.
556     */
557    @Override
558    public int hashCode() {
559        int result = 193;
560        result = 37 * result
561                + (int) (this.baseMillis ^ (this.baseMillis >>> 32));
562        result = 37 * result + this.positivePrefix.hashCode();
563        result = 37 * result + this.daySuffix.hashCode();
564        result = 37 * result + this.hourSuffix.hashCode();
565        result = 37 * result + this.minuteSuffix.hashCode();
566        result = 37 * result + this.secondSuffix.hashCode();
567        result = 37 * result + this.secondFormatter.hashCode();
568        return result;
569    }
570
571    /**
572     * Returns a clone of this instance.
573     *
574     * @return A clone.
575     */
576    @Override
577    public Object clone() {
578        RelativeDateFormat clone = (RelativeDateFormat) super.clone();
579        clone.dayFormatter = (NumberFormat) this.dayFormatter.clone();
580        clone.secondFormatter = (NumberFormat) this.secondFormatter.clone();
581        return clone;
582    }
583
584}