PageRenderTime 28ms CodeModel.GetById 16ms app.highlight 10ms RepoModel.GetById 1ms app.codeStats 0ms

/libformula-1.1.3/source/org/pentaho/reporting/libraries/formula/function/datetime/DateDifFunction.java

#
Java | 181 lines | 116 code | 24 blank | 41 comment | 19 complexity | 76bb9e7549cc13473dabab5a9ab28093 MD5 | raw file
Possible License(s): LGPL-2.1
  1/*
  2 * This program is free software; you can redistribute it and/or modify it under the
  3 * terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software
  4 * Foundation.
  5 *
  6 * You should have received a copy of the GNU Lesser General Public License along with this
  7 * program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
  8 * or from the Free Software Foundation, Inc.,
  9 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 10 *
 11 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 12 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 13 * See the GNU Lesser General Public License for more details.
 14 *
 15 * Copyright (c) 2006 - 2009 Pentaho Corporation and Contributors.  All rights reserved.
 16 */
 17
 18package org.pentaho.reporting.libraries.formula.function.datetime;
 19
 20import java.util.Calendar;
 21import java.util.Date;
 22import java.util.GregorianCalendar;
 23import java.util.Locale;
 24import java.util.TimeZone;
 25import java.math.BigDecimal;
 26
 27import org.pentaho.reporting.libraries.formula.EvaluationException;
 28import org.pentaho.reporting.libraries.formula.FormulaContext;
 29import org.pentaho.reporting.libraries.formula.LibFormulaErrorValue;
 30import org.pentaho.reporting.libraries.formula.LocalizationContext;
 31import org.pentaho.reporting.libraries.formula.util.NumberUtil;
 32import org.pentaho.reporting.libraries.formula.function.Function;
 33import org.pentaho.reporting.libraries.formula.function.ParameterCallback;
 34import org.pentaho.reporting.libraries.formula.lvalues.TypeValuePair;
 35import org.pentaho.reporting.libraries.formula.typing.TypeRegistry;
 36import org.pentaho.reporting.libraries.formula.typing.coretypes.NumberType;
 37
 38/**
 39 * This function returns the number of years, months, or days between two date
 40 * numbers.<br/>
 41 * <p/>
 42 * The Format is a code from the following table, entered as text, that
 43 * specifies the format you want: <TABLE> <TR> <TH>format</TH> <TH>Returns the
 44 * number of</TH> </TR> <TR> <TD>y</TD> <TD>Years</TD> </TR> <TR> <TD>m</TD>
 45 * <TD>Months. If there is not a complete month between the dates, 0 will be
 46 * returned.</TD> </TR> <TR> <TD>d</TD> <TD>Days</TD> </TR> <TR> <TD>md</TD>
 47 * <TD>Days, ignoring months and years</TD> </TR> <TR> <TD>ym</TD> <TD>Months,
 48 * ignoring years</TD> </TR> <TR> <TD>yd</TD> <TD>Days, ignoring years</TD>
 49 * </TR> <TR> <TD></TD> <TD></TD> </TR> </TABLE>
 50 *
 51 * @author Cedric Pronzato
 52 */
 53public class DateDifFunction implements Function
 54{
 55  public static final String YEARS_CODE = "y";
 56  public static final String MONTHS_CODE = "m";
 57  public static final String DAYS_CODE = "d";
 58  public static final String DAYS_IGNORING_YEARS = "yd";
 59  public static final String MONTHS_IGNORING_YEARS = "ym";
 60  public static final String DAYS_IGNORING_MONTHS_YEARS = "md";
 61  private static final long serialVersionUID = 81013707499607068L;
 62
 63  public DateDifFunction()
 64  {
 65  }
 66
 67  public String getCanonicalName()
 68  {
 69    return "DATEDIF";
 70  }
 71
 72  public TypeValuePair evaluate(final FormulaContext context,
 73                                final ParameterCallback parameters)
 74      throws EvaluationException
 75  {
 76    if (parameters.getParameterCount() != 3)
 77    {
 78      throw EvaluationException.getInstance(LibFormulaErrorValue.ERROR_ARGUMENTS_VALUE);
 79    }
 80
 81    final TypeRegistry typeRegistry = context.getTypeRegistry();
 82    final String formatCode = typeRegistry.convertToText
 83        (parameters.getType(2), parameters.getValue(2));
 84
 85    if (formatCode == null || "".equals(formatCode))
 86    {
 87      throw EvaluationException.getInstance(
 88          LibFormulaErrorValue.ERROR_INVALID_ARGUMENT_VALUE);
 89    }
 90
 91    if (DateDifFunction.DAYS_CODE.equals(formatCode))
 92    {
 93      final Number date1 = typeRegistry.convertToNumber
 94          (parameters.getType(0), parameters.getValue(0));
 95      final Number date2 = typeRegistry.convertToNumber
 96          (parameters.getType(1), parameters.getValue(1));
 97
 98      final BigDecimal dn1 = NumberUtil.performIntRounding(NumberUtil.getAsBigDecimal(date1));
 99      final BigDecimal dn2 = NumberUtil.performIntRounding(NumberUtil.getAsBigDecimal(date2));
100      //noinspection UnpredictableBigDecimalConstructorCall
101      return new TypeValuePair(NumberType.GENERIC_NUMBER, new BigDecimal(dn2.longValue() - dn1.longValue()));
102    }
103
104    final Date date1 = typeRegistry.convertToDate
105        (parameters.getType(0), parameters.getValue(0));
106    final Date date2 = typeRegistry.convertToDate
107        (parameters.getType(1), parameters.getValue(1));
108
109    if (date1 == null || date2 == null)
110    {
111      throw EvaluationException.getInstance(LibFormulaErrorValue.ERROR_INVALID_ARGUMENT_VALUE);
112    }
113
114    final LocalizationContext localizationContext = context.getLocalizationContext();
115    final TimeZone timeZone = localizationContext.getTimeZone();
116    final Locale locale = localizationContext.getLocale();
117    final GregorianCalendar calandar1 =
118        new GregorianCalendar(timeZone, locale);
119    calandar1.setTime(date1);
120
121    final GregorianCalendar calandar2 =
122        new GregorianCalendar(timeZone, locale);
123    calandar2.setTime(date2);
124
125    final int res;
126
127    if (DateDifFunction.YEARS_CODE.equals(formatCode))
128    {
129      res = Math.abs(calandar2.get(Calendar.YEAR) - calandar1.get(Calendar.YEAR));
130    }
131    else if (DateDifFunction.MONTHS_CODE.equals(formatCode))
132    {
133      final int month1 = calandar1.get(Calendar.MONTH);
134      final int month2 = calandar2.get(Calendar.MONTH);
135      final int year1 = calandar1.get(Calendar.YEAR);
136      final int year2 = calandar2.get(Calendar.YEAR);
137
138      res = Math.abs(year2 - year1) * 12 + Math.abs(month2 - month1);
139    }
140    else if (DateDifFunction.DAYS_IGNORING_MONTHS_YEARS.equals(formatCode))
141    {
142      // The number of days between Date1 and Date2, as if Date1 and
143      // Date2 were in the same month and the same year.
144
145      // Not sure what happens to leap years, so this solution may be invalid.
146      calandar1.set(Calendar.YEAR, calandar2.get(Calendar.YEAR));
147      calandar1.set(Calendar.MONTH, calandar2.get(Calendar.MONTH));
148
149      res = Math.abs(calandar2.get(Calendar.DAY_OF_MONTH) -
150                     calandar1.get(Calendar.DAY_OF_MONTH));
151    }
152    else if (DateDifFunction.MONTHS_IGNORING_YEARS.equals(formatCode))
153    {
154      final int month1 = calandar1.get(Calendar.MONTH);
155      final int month2 = calandar2.get(Calendar.MONTH);
156
157      res = Math.abs(month2 - month1);
158    }
159    else if (DateDifFunction.DAYS_IGNORING_YEARS.equals(formatCode))
160    {
161      //Isn't that a stupid case? How could we count the days while ignoring
162      //how much days there are in each months without using the year?
163
164      // The number of days between Date1 and Date2, as if Date1 and Date2
165      // were in the same year.
166
167      // Not sure what happens to leap years, so this solution may be invalid.
168      calandar1.set(Calendar.YEAR, calandar2.get(Calendar.YEAR));
169      final int dayOne = calandar1.get(Calendar.DAY_OF_YEAR);
170      final int dayTwo = calandar2.get(Calendar.DAY_OF_YEAR);
171      res = Math.abs(dayOne - dayTwo);
172    }
173    else
174    {
175      throw EvaluationException.getInstance(LibFormulaErrorValue.ERROR_INVALID_ARGUMENT_VALUE);
176    }
177
178    //noinspection UnpredictableBigDecimalConstructorCall
179    return new TypeValuePair(NumberType.GENERIC_NUMBER, new BigDecimal((double) res));
180  }
181}