示例#1
0
 /**
  * Creates a periodic frequency.
  *
  * @param period the period to represent
  * @param name the name
  */
 private Frequency(Period period, String name) {
   ArgChecker.notNull(period, "period");
   ArgChecker.isFalse(period.isZero(), "Period must not be zero");
   ArgChecker.isFalse(period.isNegative(), "Period must not be negative");
   this.period = period;
   this.name = name;
 }
示例#2
0
  public static void main(String[] args) {
    LocalDate hoje = LocalDate.now();
    System.out.println(hoje);

    LocalDate olimpiadasRio = LocalDate.of(2016, Month.JUNE, 5);
    System.out.println(olimpiadasRio);

    int dias = olimpiadasRio.getDayOfYear() - hoje.getDayOfYear();
    System.out.println(dias + " dias para as Olímpiadas no Rio!");

    Period periodo = Period.between(hoje, olimpiadasRio);
    System.out.println(periodo.getMonths() + " meses e " + periodo.getDays() + " dias.");

    DateTimeFormatter formatador = DateTimeFormatter.ofPattern("dd/MM/yyyy");
    String valorFormatado = olimpiadasRio.format(formatador);
    System.out.println(valorFormatado);

    System.out.println(" --- Medida de tempo ---");

    DateTimeFormatter formatadorComHoras = DateTimeFormatter.ofPattern("dd/MM/yyyy hh:mm:ss");
    LocalDateTime agora = LocalDateTime.now();
    System.out.println(agora);
    System.out.println(agora.format(formatadorComHoras));

    LocalTime intervalo = LocalTime.of(12, 30);
    System.out.println(intervalo);
  }
示例#3
0
  /**
   * Make a set of standard CDS represented as a MultiCdsAnalytic instance. The maturities of the
   * CDS are measured from the next IMM date (after the trade date), and the tenors are the given
   * matIndices multiplied by the coupon interval (3 months).
   *
   * @param tradeDate the trade date
   * @param accStartDate the accrual start date
   * @param matIndices the CDS tenors are these multiplied by the coupon interval (3 months)
   * @return a set of CDS represented as a MultiCdsAnalytic
   */
  public MultiCdsAnalytic makeMultiImmCds(
      LocalDate tradeDate, LocalDate accStartDate, int[] matIndices) {
    if (!_couponInterval.equals(DEFAULT_COUPON_INT)) {
      throw new IllegalArgumentException(
          "coupon interval must be 3M for this method. However it is set to "
              + _couponInterval.toString());
    }
    ArgChecker.notNull(tradeDate, "tradeDate");
    ArgChecker.notEmpty(matIndices, "matIndicies");

    LocalDate nextIMM = ImmDateLogic.getNextIMMDate(tradeDate);
    LocalDate stepinDate = tradeDate.plusDays(_stepIn);
    LocalDate valueDate = addWorkDays(tradeDate, _cashSettle, _calendar);

    return new MultiCdsAnalytic(
        tradeDate,
        stepinDate,
        valueDate,
        accStartDate,
        nextIMM,
        matIndices,
        _payAccOnDefault,
        _couponIntervalTenor,
        _stubType,
        _protectStart,
        _recoveryRate,
        _businessdayAdjustmentConvention,
        DEFAULT_CALENDAR,
        _accrualDayCount,
        _curveDayCount);
  }
  private void calibration_market_quote_sensitivity_check(
      Function<MarketData, ImmutableRatesProvider> calibrator, double shift) {

    double notional = 100_000_000.0;
    double fx = 1.1111;
    double fxPts = 0.0012;
    FxSwapTrade trade =
        EUR_USD.toTrade(
            VAL_DATE, Period.ofWeeks(6), Period.ofMonths(5), BuySell.BUY, notional, fx, fxPts);
    ImmutableRatesProvider result =
        CALIBRATOR.calibrate(CURVE_GROUP_CONFIG, VAL_DATE, ALL_QUOTES, TS);
    PointSensitivities pts = FX_PRICER.presentValueSensitivity(trade.getProduct(), result);
    CurveCurrencyParameterSensitivities ps = result.curveParameterSensitivity(pts);
    CurveCurrencyParameterSensitivities mqs = MQC.sensitivity(ps, result);
    double pvUsd = FX_PRICER.presentValue(trade.getProduct(), result).getAmount(USD).getAmount();
    double pvEur = FX_PRICER.presentValue(trade.getProduct(), result).getAmount(EUR).getAmount();
    double[] mqsUsd1Computed =
        mqs.getSensitivity(USD_DSCON_CURVE_NAME, USD).getSensitivity().toArray();
    for (int i = 0; i < USD_DSC_NB_NODES; i++) {
      Map<MarketDataKey<?>, Object> map = new HashMap<>(ALL_QUOTES.getValues());
      map.put(
          QuoteKey.of(StandardId.of(SCHEME, USD_DSC_ID_VALUE[i])),
          USD_DSC_MARKET_QUOTES[i] + shift);
      ImmutableMarketData marketData = ImmutableMarketData.of(map);
      ImmutableRatesProvider rpShifted = calibrator.apply(marketData);
      double pvS = FX_PRICER.presentValue(trade.getProduct(), rpShifted).getAmount(USD).getAmount();
      assertEquals(mqsUsd1Computed[i], (pvS - pvUsd) / shift, TOLERANCE_PV_DELTA);
    }
    double[] mqsUsd2Computed =
        mqs.getSensitivity(USD_DSCON_CURVE_NAME, EUR).getSensitivity().toArray();
    for (int i = 0; i < USD_DSC_NB_NODES; i++) {
      Map<MarketDataKey<?>, Object> map = new HashMap<>(ALL_QUOTES.getValues());
      map.put(
          QuoteKey.of(StandardId.of(SCHEME, USD_DSC_ID_VALUE[i])),
          USD_DSC_MARKET_QUOTES[i] + shift);
      ImmutableMarketData ov = ImmutableMarketData.of(map);
      ImmutableRatesProvider rpShifted = calibrator.apply(ov);
      double pvS = FX_PRICER.presentValue(trade.getProduct(), rpShifted).getAmount(EUR).getAmount();
      assertEquals(mqsUsd2Computed[i], (pvS - pvEur) / shift, TOLERANCE_PV_DELTA);
    }
    double[] mqsEur1Computed =
        mqs.getSensitivity(EUR_DSC_CURVE_NAME, USD).getSensitivity().toArray();
    for (int i = 0; i < EUR_DSC_NB_NODES; i++) {
      assertEquals(mqsEur1Computed[i], 0.0, TOLERANCE_PV_DELTA);
    }
    double[] mqsEur2Computed =
        mqs.getSensitivity(EUR_DSC_CURVE_NAME, EUR).getSensitivity().toArray();
    for (int i = 0; i < EUR_DSC_NB_NODES; i++) {
      Map<MarketDataKey<?>, Object> map = new HashMap<>(ALL_QUOTES.getValues());
      map.put(
          QuoteKey.of(StandardId.of(SCHEME, EUR_DSC_ID_VALUE[i])),
          EUR_DSC_MARKET_QUOTES[i] + shift);
      ImmutableMarketData marketData = ImmutableMarketData.of(map);
      ImmutableRatesProvider rpShifted = calibrator.apply(marketData);
      double pvS = FX_PRICER.presentValue(trade.getProduct(), rpShifted).getAmount(EUR).getAmount();
      assertEquals(mqsEur2Computed[i], (pvS - pvEur) / shift, TOLERANCE_PV_DELTA, "Node " + i);
    }
  }
示例#5
0
 /**
  * Adds the period of this frequency to the specified date.
  *
  * <p>This method implements {@link TemporalAmount}. It is not intended to be called directly. Use
  * {@link LocalDate#plus(TemporalAmount)} instead.
  *
  * @param temporal the temporal object to add to
  * @return the result with this frequency added
  * @throws DateTimeException if unable to add
  * @throws ArithmeticException if numeric overflow occurs
  */
 @Override
 public Temporal addTo(Temporal temporal) {
   // special case for performance
   if (temporal instanceof LocalDate) {
     LocalDate date = (LocalDate) temporal;
     return date.plusMonths(period.toTotalMonths()).plusDays(period.getDays());
   }
   return period.addTo(temporal);
 }
示例#6
0
 /**
  * Subtracts the period of this frequency from the specified date.
  *
  * <p>This method implements {@link TemporalAmount}. It is not intended to be called directly. Use
  * {@link LocalDate#minus(TemporalAmount)} instead.
  *
  * @param temporal the temporal object to subtract from
  * @return the result with this frequency subtracted
  * @throws DateTimeException if unable to subtract
  * @throws ArithmeticException if numeric overflow occurs
  */
 @Override
 public Temporal subtractFrom(Temporal temporal) {
   // special case for performance
   if (temporal instanceof LocalDate) {
     LocalDate date = (LocalDate) temporal;
     return date.minusMonths(period.toTotalMonths()).minusDays(period.getDays());
   }
   return period.subtractFrom(temporal);
 }
 @Test
 public void testGetAge() {
   LocalDate now = LocalDate.now();
   int currentYear = now.getYear();
   LocalDate birthDate = LocalDate.of(2010, 2, 1);
   Period age = AgeUtils.getAge(birthDate); // P6Y1M21D
   Assert.assertEquals(currentYear - birthDate.getYear(), age.getYears());
   Assert.assertEquals(now.getMonthValue() - birthDate.getMonthValue(), age.getMonths());
   Assert.assertEquals(now.getDayOfMonth() - birthDate.getDayOfMonth(), age.getDays());
 }
示例#8
0
 /**
  * Obtains a periodic frequency from a {@code Period}.
  *
  * <p>The period normally consists of either days and weeks, or months and years. It must also be
  * positive and non-zero.
  *
  * <p>If the number of days is an exact multiple of 7 it will be converted to weeks. Months are
  * not normalized into years.
  *
  * <p>The maximum tenor length is 1,000 years.
  *
  * @param period the period to convert to a periodic frequency
  * @return the periodic frequency
  * @throws IllegalArgumentException if the period is negative, zero or too large
  */
 public static Frequency of(Period period) {
   ArgChecker.notNull(period, "period");
   int days = period.getDays();
   long months = period.toTotalMonths();
   if (months == 0 && days != 0) {
     return ofDays(days);
   }
   if (months > MAX_MONTHS) {
     throw new IllegalArgumentException("Period must not exceed 1000 years");
   }
   return new Frequency(period);
 }
  public static void main(String[] args) {
    Period period = Period.of(1, 2, 3); // 1 year, 2 months, 3 days
    Period periodTwoMonths = Period.ofMonths(2);
    System.out.println(period);
    System.out.println(periodTwoMonths);
    Period period20142015 =
        Period.between(LocalDate.of(2014, Month.JANUARY, 1), LocalDate.of(2015, Month.JANUARY, 1));
    Period period20152014 =
        Period.between(LocalDate.of(2015, Month.JANUARY, 1), LocalDate.of(2014, Month.JANUARY, 1));

    System.out.println("2014-2015:" + period20142015);
    System.out.println("2015-2014:" + period20152014);
  }
 private String readablePeriod(Period period) {
   if (period.isZero()) return "Hoy";
   String startsWith = period.isNegative() ? "Hace " : "En ";
   long months = Math.abs(period.toTotalMonths());
   int days = Math.abs(period.getDays());
   if (Math.abs(months) > 0) {
     String endsWith = (months > 1) ? "es" : "";
     return startsWith + months + " mes" + endsWith;
   } else {
     String endsWith = (days > 1) ? "s" : "";
     return startsWith + days + " dia" + endsWith;
   }
 }
示例#11
0
 /**
  * Calculates the number of events that occur in a year.
  *
  * <p>The number of events per year is the number of times that the period occurs per year. Not
  * all periodic frequency instances can be converted to an integer events per year. All constants
  * declared on this class will return a result.
  *
  * <p>Month-based and year-based periodic frequencies are converted by dividing 12 by the number
  * of months. Only the following periodic frequencies return a value - P1M, P2M, P3M, P4M, P6M,
  * P1Y.
  *
  * <p>Day-based and week-based periodic frequencies are converted by dividing 364 by the number of
  * days. Only the following periodic frequencies return a value - P1D, P2D, P4D, P1W, P2W, P4W,
  * P13W, P26W, P52W.
  *
  * <p>The 'Term' periodic frequency returns zero.
  *
  * @return the number of events per year
  * @throws IllegalArgumentException if unable to calculate the number of events per year
  */
 public int eventsPerYear() {
   if (isTerm()) {
     return 0;
   }
   long months = period.toTotalMonths();
   int days = period.getDays();
   if (isMonthBased()) {
     if (12 % months == 0) {
       return (int) (12 / months);
     }
   } else if (months == 0 && 364 % days == 0) {
     return (int) (364 / days);
   }
   throw new IllegalArgumentException("Unable to calculate events per year: " + this);
 }
示例#12
0
 /**
  * Make a set of standard CDS represented as a MultiCdsAnalytic instance. The first CDS with have
  * a tenor of firstTenor, while the last CDS will have a tenor of lastTenor; the remaining CDS
  * will consist of all the (multiple of 3 month) tenors between the first and last tenor, e.g. if
  * firstTenor = 6M and lastTenor = 5Y, there will be a total of 22 CDS with tenors of 6M, 9M,
  * 1Y,....4Y9M, 5Y.
  *
  * @param tradeDate the trade date
  * @param firstTenor the first tenor
  * @param lastTenor the last tenor
  * @return a set of CDS represented as a MultiCdsAnalytic
  */
 public MultiCdsAnalytic makeMultiImmCds(
     LocalDate tradeDate, Period firstTenor, Period lastTenor) {
   ArgChecker.notNull(firstTenor, "firstTenor");
   ArgChecker.notNull(lastTenor, "lastTenor");
   int immNMonths = (int) DEFAULT_COUPON_INT.toTotalMonths();
   int m1 = (int) firstTenor.toTotalMonths();
   int m2 = (int) lastTenor.toTotalMonths();
   if (m1 % immNMonths != 0 || m2 % immNMonths != 0) {
     throw new IllegalArgumentException(
         "tenors is not a multiple of " + DEFAULT_COUPON_INT.toString());
   }
   int firstIndex = m1 / immNMonths;
   int lastIndex = m2 / immNMonths;
   return makeMultiImmCds(tradeDate, firstIndex, lastIndex);
 }
 @Test
 public void testGetNextFirstOrFifteenthOfTheMonthWithNullBaseDateReturnsValue() {
   LocalDate today = LocalDate.now();
   LocalDate adjustmentDate = AmortizationCalculator.getNextFirstOrFifteenthOfTheMonth(null);
   long daysBetween = Period.between(today, adjustmentDate).getDays();
   assertTrue("Adjustment date from the 1st should remain on the 1st", daysBetween <= 16);
 }
 public void test_toTrade() {
   IborFixingDepositConvention convention =
       ImmutableIborFixingDepositConvention.builder()
           .businessDayAdjustment(BDA_MOD_FOLLOW)
           .currency(EUR)
           .dayCount(ACT_365F)
           .fixingDateOffset(FIXING_ADJ)
           .index(EUR_LIBOR_3M)
           .spotDateOffset(SPOT_ADJ)
           .build();
   LocalDate tradeDate = LocalDate.of(2015, 1, 22);
   Period depositPeriod = Period.ofMonths(3);
   double notional = 1d;
   double fixedRate = 0.045;
   IborFixingDepositTrade trade =
       convention.toTrade(tradeDate, depositPeriod, BUY, notional, fixedRate);
   LocalDate startExpected = SPOT_ADJ.adjust(tradeDate);
   LocalDate endExpected = startExpected.plus(depositPeriod);
   IborFixingDeposit productExpected =
       IborFixingDeposit.builder()
           .businessDayAdjustment(BDA_MOD_FOLLOW)
           .buySell(BUY)
           .currency(EUR)
           .dayCount(ACT_365F)
           .startDate(startExpected)
           .endDate(endExpected)
           .fixedRate(fixedRate)
           .fixingDateOffset(FIXING_ADJ)
           .index(EUR_LIBOR_3M)
           .notional(notional)
           .build();
   TradeInfo tradeInfoExpected = TradeInfo.builder().tradeDate(tradeDate).build();
   assertEquals(trade.getProduct(), productExpected);
   assertEquals(trade.getTradeInfo(), tradeInfoExpected);
 }
示例#15
0
  @Test
  public void testBasic() {
    System.out.println(Year.now());
    System.out.println(Year.of(2015));
    System.out.println(Year.isLeap(2016));

    Locale locale = Locale.getDefault();
    System.out.println(Month.DECEMBER.getDisplayName(TextStyle.FULL, locale));
    System.out.println(Month.DECEMBER.getDisplayName(TextStyle.SHORT, locale));
    System.out.println(Month.DECEMBER.getDisplayName(TextStyle.NARROW, locale));
    System.out.println(Month.DECEMBER.getDisplayName(TextStyle.FULL_STANDALONE, locale));
    System.out.println(Month.of(8).ordinal());
    System.out.println(Month.AUGUST.minus(2));

    System.out.println(YearMonth.now());
    System.out.println(MonthDay.now());

    System.out.println(DayOfWeek.FRIDAY.plus(2));
    System.out.println(DayOfWeek.of(1));
    System.out.println(
        DayOfWeek.from(LocalDateTime.ofInstant(Instant.now(), ZoneId.systemDefault())));

    System.out.println(Period.between(Year.now().atDay(1), LocalDate.now()));
    System.out.println(ChronoUnit.DAYS.between(Year.now().atDay(1), LocalDate.now()));
  }
 static {
   USD_DSC_NODES[0] =
       TermDepositCurveNode.of(
           TermDepositTemplate.of(Period.ofDays(1), USD_DEPOSIT_T0),
           QuoteKey.of(StandardId.of(SCHEME, USD_DSC_ID_VALUE[0])));
   USD_DSC_NODES[1] =
       TermDepositCurveNode.of(
           TermDepositTemplate.of(Period.ofDays(1), USD_DEPOSIT_T1),
           QuoteKey.of(StandardId.of(SCHEME, USD_DSC_ID_VALUE[1])));
   for (int i = 0; i < USD_DSC_NB_OIS_NODES; i++) {
     USD_DSC_NODES[USD_DSC_NB_DEPO_NODES + i] =
         FixedOvernightSwapCurveNode.of(
             FixedOvernightSwapTemplate.of(
                 Period.ZERO, Tenor.of(USD_DSC_OIS_TENORS[i]), USD_FIXED_1Y_FED_FUND_OIS),
             QuoteKey.of(StandardId.of(SCHEME, USD_DSC_ID_VALUE[USD_DSC_NB_DEPO_NODES + i])));
   }
 }
示例#17
0
  public Period calculateSeniority() {

    LocalDate hireDate = this.getHireDate();
    if (hireDate == null) return null;

    LocalDate now = LocalDate.now();
    return Period.between(hireDate, now);
  }
 // -------------------------------------------------------------------------
 public void coverage() {
   TermDepositCurveNode test = TermDepositCurveNode.of(TEMPLATE, QUOTE_ID, SPREAD);
   coverImmutableBean(test);
   TermDepositCurveNode test2 =
       TermDepositCurveNode.of(
           TermDepositTemplate.of(Period.ofMonths(1), CONVENTION),
           QuoteId.of(StandardId.of("OG-Ticker", "Deposit2")));
   coverBeanEquals(test, test2);
 }
示例#19
0
/** Test {@link CurveGroupEntry}. */
@Test
public class CurveGroupEntryTest {

  private static final InterpolatedNodalCurveDefinition CURVE_DEFN =
      InterpolatedNodalCurveDefinition.builder()
          .name(CurveName.of("Test"))
          .xValueType(ValueType.YEAR_FRACTION)
          .yValueType(ValueType.ZERO_RATE)
          .dayCount(ACT_365F)
          .nodes(
              ImmutableList.of(
                  DummyFraCurveNode.of(
                      Period.ofMonths(1),
                      GBP_LIBOR_1M,
                      QuoteKey.of(StandardId.of("OG", "Ticker")))))
          .interpolator(CurveInterpolators.LINEAR)
          .extrapolatorLeft(CurveExtrapolators.FLAT)
          .extrapolatorRight(CurveExtrapolators.FLAT)
          .build();
  private static final InterpolatedNodalCurveDefinition CURVE_DEFN2 =
      CURVE_DEFN.toBuilder().name(CurveName.of("Test2")).build();

  public void test_builder() {
    CurveGroupEntry test =
        CurveGroupEntry.builder()
            .curveDefinition(CURVE_DEFN)
            .discountCurrencies(GBP)
            .iborIndices(GBP_LIBOR_1M, GBP_LIBOR_3M)
            .overnightIndices(GBP_SONIA)
            .build();
    assertEquals(test.getCurveDefinition(), CURVE_DEFN);
    assertEquals(test.getDiscountCurrencies(), ImmutableSet.of(GBP));
    assertEquals(test.getIborIndices(), ImmutableSet.of(GBP_LIBOR_1M, GBP_LIBOR_3M));
    assertEquals(test.getOvernightIndices(), ImmutableSet.of(GBP_SONIA));
  }

  // -------------------------------------------------------------------------
  public void coverage() {
    CurveGroupEntry test =
        CurveGroupEntry.builder().curveDefinition(CURVE_DEFN).discountCurrencies(GBP).build();
    coverImmutableBean(test);
    CurveGroupEntry test2 =
        CurveGroupEntry.builder()
            .curveDefinition(CURVE_DEFN2)
            .iborIndices(GBP_LIBOR_1M)
            .overnightIndices(GBP_SONIA)
            .build();
    coverBeanEquals(test, test2);
  }

  public void test_serialization() {
    CurveGroupEntry test =
        CurveGroupEntry.builder().curveDefinition(CURVE_DEFN).discountCurrencies(GBP).build();
    assertSerialization(test);
  }
}
示例#20
0
  /**
   * Make a set of standard CDS represented as a MultiCdsAnalytic instance.
   *
   * @param tradeDate the trade date
   * @param accStartDate the accrual start date
   * @param tenors the tenors (length) of the CDS
   * @return a set of CDS represented as a MultiCdsAnalytic
   */
  public MultiCdsAnalytic makeMultiImmCds(
      LocalDate tradeDate, LocalDate accStartDate, Period[] tenors) {

    ArgChecker.noNulls(tenors, "tenors");
    int n = tenors.length;

    int immNMonths = (int) DEFAULT_COUPON_INT.toTotalMonths();
    int[] matIndices = new int[n];
    for (int i = 0; i < n; i++) {
      int months = (int) tenors[i].toTotalMonths();
      if (months % immNMonths != 0) {
        throw new IllegalArgumentException(
            "tenors index " + i + " is not a multiple of " + DEFAULT_COUPON_INT.toString());
      }
      matIndices[i] = months / immNMonths;
    }

    return makeMultiImmCds(tradeDate, accStartDate, matIndices);
  }
示例#21
0
  private LocalDate getMaxMonthsThresholdDate(ExcelRow item) {
    LocalDate result = null;

    if (item.getDate() != null) {
      if (firstDate == null || firstDate.isAfter(item.getDate())) {
        firstDate = item.getDate();
      }

      final LocalDate startDate = firstDate;
      final LocalDate endDate = LocalDate.now();
      final Period period = Period.between(startDate, endDate);

      /** If the period between the first date and today is greater or equal to maxNumberOfMonth */
      if (period.toTotalMonths() >= maxNumberOfMonth) {
        result = endDate;
      }
    }

    return result;
  }
示例#22
0
 /**
  * Checks if this periodic frequency equals another periodic frequency.
  *
  * <p>The comparison checks the frequency period.
  *
  * @param obj the other frequency, null returns false
  * @return true if equal
  */
 @Override
 public boolean equals(Object obj) {
   if (obj == this) {
     return true;
   }
   if (obj == null || getClass() != obj.getClass()) {
     return false;
   }
   Frequency other = (Frequency) obj;
   return period.equals(other.period);
 }
示例#23
0
 @Test
 public void testModifierDuree() {
   PeriodDateHeure periode1 =
       new PeriodDateHeure(
           LocalDateTime.parse("2000-01-01T00:00:00"), LocalDateTime.parse("2000-01-05T00:00:00"));
   PeriodDateHeure periode2 = periode1.modifierDuree(Period.ofDays(15));
   Assert.assertEquals(
       new PeriodDateHeure(
           LocalDateTime.parse("2000-01-01T00:00:00"), LocalDateTime.parse("2000-01-16T00:00:00")),
       periode2);
 }
  @Test
  public void testInsert() {

    SomePeriodBean bean = new SomePeriodBean();
    bean.setPeriod(Period.of(3, 4, 5));
    bean.setAnniversary(MonthDay.of(4, 29));
    Ebean.save(bean);

    SomePeriodBean bean1 = Ebean.find(SomePeriodBean.class, bean.getId());
    assertEquals(bean.getPeriod(), bean1.getPeriod());
    assertEquals(bean.getAnniversary(), bean1.getAnniversary());

    // insert fetch null value
    SomePeriodBean bean2 = new SomePeriodBean();
    Ebean.save(bean2);

    SomePeriodBean bean3 = Ebean.find(SomePeriodBean.class, bean2.getId());
    assertNull(bean3.getPeriod());
    assertNull(bean3.getAnniversary());

    List<SomePeriodBean> anniversaryList =
        Ebean.find(SomePeriodBean.class)
            .where()
            .eq("anniversary", MonthDay.of(4, 29))
            .eq("period_years", 3)
            .eq("period_months", 4)
            .findList();

    assertEquals(1, anniversaryList.size());

    // must use year 2000 for range predicates
    // ... using 2001 here so not finding anything
    anniversaryList =
        Ebean.find(SomePeriodBean.class)
            .where()
            .gt("anniversary", Date.valueOf(LocalDate.of(2001, 4, 29)))
            .findList();

    assertEquals(0, anniversaryList.size());

    // can use year 2000 for range predicates
    // ... and can use LocalDate to bind
    anniversaryList =
        Ebean.find(SomePeriodBean.class)
            .where()
            .gt("anniversary", LocalDate.of(2000, 4, 22))
            .findList();

    assertEquals(1, anniversaryList.size());

    Ebean.delete(bean);
    Ebean.delete(bean2);
  }
示例#25
0
  @Test
  public void shouldPlayWithDates() {
    LocalDate d1 = LocalDate.now();
    LocalDate d2 = LocalDate.of(2014, 2, 15).plusDays(10);
    print(d1);
    print(d2);

    LocalDateTime d3 = d2.atTime(13, 23, 34, 45);
    assertThat(d3.toString(), is("2014-02-25T13:23:34.000000045"));
    LocalDateTime d4 = d3.plus(Period.of(1, 2, 3));
    assertThat(d4.toString(), is("2015-04-28T13:23:34.000000045"));
  }
  @Override
  public String convert(LocalDateTime dateTime) {
    LocalDateTime now = LocalDateTime.now();
    Duration duration = Duration.between(dateTime, now);

    Period period = Period.between(dateTime.toLocalDate(), now.toLocalDate());

    if (duration.toMinutes() < 1) {
      return String.format("%s secs ago", duration.getSeconds());
    }

    if (duration.toHours() < 1) {
      return String.format("%s mins ago", duration.toMinutes());
    }

    if (duration.toDays() < 1) {
      return String.format("%s hrs ago", duration.toHours());
    }

    if (period.getYears() > 0) {
      return DateTimeFormatter.ISO_LOCAL_DATE.format(dateTime);
    }

    if (period.getMonths() > 0) {
      return String.format("%s months ago", period.getMonths());
    }

    return String.format("%s days ago", period.getDays());
  }
示例#27
0
  @Test
  public void testGetAgeDetails() {
    LocalDate to = LocalDate.of(2011, 1, 10);

    LocalDate from = LocalDate.of(2010, 1, 10);
    Period age = AgeUtils.getAge(from, to);
    Assert.assertEquals(1, age.getYears());
    Assert.assertEquals(0, age.getMonths());
    Assert.assertEquals(0, age.getDays());

    from = LocalDate.of(2010, 1, 11);
    age = AgeUtils.getAge(from, to);
    Assert.assertEquals(0, age.getYears());
    Assert.assertEquals(11, age.getMonths());
    Assert.assertEquals(30, age.getDays());

    from = LocalDate.of(2010, 5, 11);
    age = AgeUtils.getAge(from, to);
    Assert.assertEquals(0, age.getYears());
    Assert.assertEquals(7, age.getMonths());
    Assert.assertEquals(30, age.getDays());
  }
示例#28
0
 /**
  * Parses a formatted string representing the frequency.
  *
  * <p>The format can either be based on ISO-8601, such as 'P3M' or without the 'P' prefix e.g.
  * '2W'.
  *
  * <p>The period must be positive and non-zero.
  *
  * @param toParse the string representing the frequency
  * @return the frequency
  * @throws IllegalArgumentException if the frequency cannot be parsed
  */
 @FromString
 public static Frequency parse(String toParse) {
   ArgChecker.notNull(toParse, "toParse");
   if (toParse.equalsIgnoreCase("Term")) {
     return TERM;
   }
   String prefixed = toParse.startsWith("P") ? toParse : "P" + toParse;
   try {
     return Frequency.of(Period.parse(prefixed));
   } catch (DateTimeParseException ex) {
     throw new IllegalArgumentException(ex);
   }
 }
示例#29
0
  private boolean checkList(Container container, List<Container> list) {

    if (list.size() == maxsize) {
      placed = false;

    } else if (list.isEmpty()) {
      list.add(container);
      placed = true;

    } else if (Period.between(list.get(list.size() - 1).getPickupDate(), container.getPickupDate())
        .isNegative()) {
      list.add(container);
      placed = true;
    } else if (Period.between(list.get(list.size() - 1).getPickupDate(), container.getPickupDate())
        .isZero()) {
      list.add(container);
      placed = true;
    } else {
      placed = false;
    }

    return placed;
  }
 public void test_toTrade_periodTenor() {
   IborIborSwapConvention base = ImmutableIborIborSwapConvention.of(NAME, IBOR3M, IBOR6M);
   LocalDate tradeDate = LocalDate.of(2015, 5, 5);
   LocalDate startDate = date(2015, 8, 7);
   LocalDate endDate = date(2025, 8, 7);
   SwapTrade test =
       base.toTrade(tradeDate, Period.ofMonths(3), TENOR_10Y, BUY, NOTIONAL_2M, 0.25d);
   Swap expected =
       Swap.of(
           IBOR3M.toLeg(startDate, endDate, PAY, NOTIONAL_2M, 0.25d),
           IBOR6M.toLeg(startDate, endDate, RECEIVE, NOTIONAL_2M));
   assertEquals(test.getTradeInfo().getTradeDate(), Optional.of(tradeDate));
   assertEquals(test.getProduct(), expected);
 }