Java Code Examples for java.time.LocalDate#lengthOfMonth()

The following examples show how to use java.time.LocalDate#lengthOfMonth() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: EveryDayOfWeekValueGenerator.java    From cron-utils with Apache License 2.0 6 votes vote down vote up
EveryDayOfWeekValueGenerator(final CronField cronField, final int year, final int month, WeekDay mondayDoWValue) {
    super(cronField);
    Preconditions.checkArgument(CronFieldName.DAY_OF_WEEK.equals(cronField.getField()), "CronField does not belong to day of week");
    this.year = year;
    this.month = month;
    final LocalDate date = LocalDate.of(year, month, 1);
    lastDayOfMonth = date.lengthOfMonth();

    // from is set by EveryFieldValueGenerator to be the first day of the week to start counting from
    // and to is set by EveryFieldValueGenerator to be the last day of the week
    // in the case of from-to/period (ex. MON-FRI/2)
    final Every every = (Every) cronField.getExpression();
    int period = every.getPeriod().getValue();
    Preconditions.checkArgument(period > 0 && period < 8, "Cron Expression for day of week has an invalid period.");
    dowValidValues = getValidDays(mondayDoWValue, period, from, to);
}
 
Example 2
Source File: DateTest.java    From java-master with Apache License 2.0 6 votes vote down vote up
@Test
public void test() {
    LocalDate date = LocalDate.of(2014, 3, 18);
    LocalTime time = LocalTime.of(10, 3, 18);
    int year = date.getYear();
    Month month = date.getMonth();
    int day = date.getDayOfMonth();
    DayOfWeek dow = date.getDayOfWeek();
    int len = date.lengthOfMonth();
    boolean leap = date.isLeapYear();
    // 还可以使用工厂方法从系统时钟中获取当前的日期:
    LocalDate today = LocalDate.now();
    // LocalDateTime,是LocalDate和LocalTime的合体。它同时表示了日期和时间,但不带有时区信息
    LocalDateTime dt1 = LocalDateTime.of(2014, Month.MARCH, 18, 13, 45, 20);
    LocalDateTime dt2 = LocalDateTime.of(date, time);
    // 也可以使用toLocalDate或者toLocalTime方法,从LocalDateTime中提取LocalDate或者LocalTime组件:
    LocalDate date1 = dt1.toLocalDate();
    LocalTime time1 = dt1.toLocalTime();

}
 
Example 3
Source File: SingleExecutionTime.java    From cron-utils with Apache License 2.0 6 votes vote down vote up
private List<Integer> generateDayCandidatesQuestionMarkSupportedUsingDoWAndDoM(final int year, final int month, final WeekDay mondayDoWValue) {
    final LocalDate date = LocalDate.of(year, month, 1);
    final int lengthOfMonth = date.lengthOfMonth();
    if (daysOfMonthCronField.getExpression() instanceof Always && daysOfWeekCronField.getExpression() instanceof Always) {
        return createDayOfMonthValueGeneratorInstance(daysOfMonthCronField, year, month)
                .generateCandidates(1, lengthOfMonth)
                .stream().distinct().sorted()
                .collect(Collectors.toList());
    } else if (daysOfMonthCronField.getExpression() instanceof QuestionMark) {
        return createDayOfWeekValueGeneratorInstance(daysOfWeekCronField, year, month, mondayDoWValue)
                .generateCandidates(1, lengthOfMonth)
                .stream().distinct().sorted()
                .collect(Collectors.toList());
    } else if (daysOfWeekCronField.getExpression() instanceof QuestionMark) {
        return createDayOfMonthValueGeneratorInstance(daysOfMonthCronField, year, month)
                .generateCandidates(1, lengthOfMonth)
                .stream().distinct().sorted()
                .collect(Collectors.toList());
    } else {
        Set<Integer> candidates = new HashSet<>(createDayOfMonthValueGeneratorInstance(daysOfMonthCronField, year, month).generateCandidates(1, lengthOfMonth));
        Set<Integer> daysOfWeek = new HashSet<>(createDayOfWeekValueGeneratorInstance(daysOfWeekCronField, year, month, mondayDoWValue).generateCandidates(1, lengthOfMonth));
        // Only the intersection of valid days from the days of week and valid days of month should be returned.
        candidates.retainAll(daysOfWeek);
        return candidates.stream().sorted().collect(Collectors.toList());
    }
}
 
Example 4
Source File: DateIndex.java    From finmath-lib with Apache License 2.0 6 votes vote down vote up
@Override
public RandomVariable getValue(final double fixingTime, final LIBORModelMonteCarloSimulationModel model) throws CalculationException {
	final LocalDate referenceDate = model.getModel().getForwardRateCurve().getReferenceDate()
			.plusDays((int)Math.round(fixingTime*365));

	double value = 0;
	switch(dateIndexType) {
	case DAY:
		value = referenceDate.getDayOfMonth();
		break;
	case MONTH:
		value = referenceDate.getMonthValue();
		break;
	case YEAR:
		value = referenceDate.getYear();
		break;
	case NUMBER_OF_DAYS_IN_MONTH:
		value = referenceDate.lengthOfMonth();
		break;
	default:
		throw new IllegalArgumentException("Unknown dateIndexType " + dateIndexType + ".");
	}

	return model.getRandomVariableForConstant(value);
}
 
Example 5
Source File: InflationRateCalculation.java    From Strata with Apache License 2.0 6 votes vote down vote up
private RateComputation createRateComputation(SchedulePeriod period, int scheduleIndex) {

    // handle where index value at start date is known
    LocalDate endDate = period.getEndDate();
    if (firstIndexValue != null && scheduleIndex == 0) {
      return createRateComputation(endDate);
    }
    YearMonth referenceStartMonth = YearMonth.from(period.getStartDate().minus(lag));
    YearMonth referenceEndMonth = YearMonth.from(endDate.minus(lag));
    if (indexCalculationMethod.equals(PriceIndexCalculationMethod.INTERPOLATED)) {
      // interpolate between data from two different months
      double weight = 1d - (endDate.getDayOfMonth() - 1d) / endDate.lengthOfMonth();
      return InflationInterpolatedRateComputation.of(index, referenceStartMonth, referenceEndMonth, weight);
    } else if (indexCalculationMethod.equals(PriceIndexCalculationMethod.MONTHLY)) {
      // no interpolation
      return InflationMonthlyRateComputation.of(index, referenceStartMonth, referenceEndMonth);
    } else {
      throw new IllegalArgumentException(
          "PriceIndexCalculationMethod " + indexCalculationMethod.toString() + " is not supported");
    }
  }
 
Example 6
Source File: DateIndex.java    From finmath-lib with Apache License 2.0 6 votes vote down vote up
@Override
public RandomVariable getValue(final double fixingTime, final LIBORModelMonteCarloSimulationModel model) throws CalculationException {
	final LocalDate referenceDate = model.getModel().getForwardRateCurve().getReferenceDate()
			.plusDays((int)Math.round(fixingTime*365));

	double value = 0;
	switch(dateIndexType) {
	case DAY:
		value = referenceDate.getDayOfMonth();
		break;
	case MONTH:
		value = referenceDate.getMonthValue();
		break;
	case YEAR:
		value = referenceDate.getYear();
		break;
	case NUMBER_OF_DAYS_IN_MONTH:
		value = referenceDate.lengthOfMonth();
		break;
	default:
		throw new IllegalArgumentException("Unknown dateIndexType " + dateIndexType + ".");
	}

	return model.getRandomVariableForConstant(value);
}
 
Example 7
Source File: LocalDateUtils.java    From Strata with Apache License 2.0 6 votes vote down vote up
/**
 * Adds a number of days to the date.
 * <p>
 * Faster than the JDK method.
 * 
 * @param date  the date to add to
 * @param daysToAdd  the days to add
 * @return the new date
 */
static LocalDate plusDays(LocalDate date, int daysToAdd) {
  if (daysToAdd == 0) {
    return date;
  }
  // add the days to the current day-of-month
  // if it is guaranteed to be in this month or the next month then fast path it
  // (59th Jan is 28th Feb, 59th Feb is 31st Mar)
  long dom = date.getDayOfMonth() + daysToAdd;
  if (dom > 0 && dom <= 59) {
    int monthLen = date.lengthOfMonth();
    int month = date.getMonthValue();
    int year = date.getYear();
    if (dom <= monthLen) {
      return LocalDate.of(year, month, (int) dom);
    } else if (month < 12) {
      return LocalDate.of(year, month + 1, (int) (dom - monthLen));
    } else {
      return LocalDate.of(year + 1, 1, (int) (dom - monthLen));
    }
  }
  long mjDay = Math.addExact(date.toEpochDay(), daysToAdd);
  return LocalDate.ofEpochDay(mjDay);
}
 
Example 8
Source File: DayCountConvention_30E_360_ISDA.java    From finmath-lib with Apache License 2.0 5 votes vote down vote up
@Override
public double getDaycount(final LocalDate startDate, final LocalDate endDate) {
	if(startDate.isAfter(endDate)) {
		return -getDaycount(endDate,startDate);
	}

	int startDateDay 	= startDate.getDayOfMonth();
	final int startDateMonth 	= startDate.getMonthValue();
	final int startDateYear 	= startDate.getYear();

	int endDateDay 		= endDate.getDayOfMonth();
	final int endDateMonth 	= endDate.getMonthValue();
	final int endDateYear 	= endDate.getYear();


	// Check if we have last day of February
	final boolean isStartDateLastDayOfFebruary = (startDateMonth == Month.FEBRUARY.getValue() && startDateDay == startDate.lengthOfMonth());
	final boolean isEndDateLastDayOfFebruary = (endDateMonth == Month.FEBRUARY.getValue() && endDateDay == endDate.lengthOfMonth());

	// Last day of February and 31st of a month are both treated as "30".
	if(isStartDateLastDayOfFebruary || startDateDay == 31) {
		startDateDay = 30;
	}
	if((isEndDateLastDayOfFebruary && !isTreatEndDateAsTerminationDate) || endDateDay == 31) {
		endDateDay = 30;
	}

	return (endDateYear - startDateYear) * 360.0 + (endDateMonth - startDateMonth) * 30.0 + (endDateDay - Math.min(startDateDay, 30.0));
}
 
Example 9
Source File: DayCountConvention_30U_360.java    From finmath-lib with Apache License 2.0 5 votes vote down vote up
@Override
public double getDaycount(final LocalDate startDate, final LocalDate endDate) {
	if(startDate.isAfter(endDate)) {
		return -getDaycount(endDate,startDate);
	}

	int startDateDay 	= startDate.getDayOfMonth();
	final int startDateMonth 	= startDate.getMonthValue();
	final int startDateYear 	= startDate.getYear();

	int endDateDay 		= endDate.getDayOfMonth();
	final int endDateMonth 	= endDate.getMonthValue();
	final int endDateYear 	= endDate.getYear();

	if(
			isEndOfMonth &&
			startDate.getMonth() == Month.FEBRUARY &&
			startDate.getDayOfMonth() == startDate.lengthOfMonth() &&
			endDate.getMonth() == Month.FEBRUARY &&
			endDate.getDayOfMonth() == endDate.lengthOfMonth()
			) {
		endDateDay = 30;
	}

	if(
			isEndOfMonth &&
			startDate.getMonth() == Month.FEBRUARY &&
			startDate.getDayOfMonth() == startDate.lengthOfMonth()
			) {
		startDateDay = 30;
	}

	if(endDateDay > 30 && startDateDay >= 30) {
		endDateDay = 30;
	}
	startDateDay = Math.min(startDateDay,30);

	return (endDateYear - startDateYear) * 360.0 + (endDateMonth - startDateMonth) * 30.0 + (endDateDay - startDateDay);
}
 
Example 10
Source File: SeasonalCurve.java    From finmath-lib with Apache License 2.0 5 votes vote down vote up
@Override
public double getValue(final AnalyticModel model, final double time) {
	final LocalDate calendar = getReferenceDate().plusDays((int) Math.round(time*365));

	final int month = calendar.getMonthValue();				// Note: month = 1,2,3,...,12
	final int day   = calendar.getDayOfMonth(); 				// Note: day = 1,2,3,...,numberOfDays
	final int numberOfDays = calendar.lengthOfMonth();
	final double season = (month-1) / 12.0 + (day-1) / (double)numberOfDays / 12.0;

	return baseCurve.getValue(model, season);
}
 
Example 11
Source File: DayCountConvention_30E_360_ISDA.java    From finmath-lib with Apache License 2.0 5 votes vote down vote up
@Override
public double getDaycount(final LocalDate startDate, final LocalDate endDate) {
	if(startDate.isAfter(endDate)) {
		return -getDaycount(endDate,startDate);
	}

	int startDateDay 	= startDate.getDayOfMonth();
	final int startDateMonth 	= startDate.getMonthValue();
	final int startDateYear 	= startDate.getYear();

	int endDateDay 		= endDate.getDayOfMonth();
	final int endDateMonth 	= endDate.getMonthValue();
	final int endDateYear 	= endDate.getYear();


	// Check if we have last day of February
	final boolean isStartDateLastDayOfFebruary = (startDateMonth == Month.FEBRUARY.getValue() && startDateDay == startDate.lengthOfMonth());
	final boolean isEndDateLastDayOfFebruary = (endDateMonth == Month.FEBRUARY.getValue() && endDateDay == endDate.lengthOfMonth());

	// Last day of February and 31st of a month are both treated as "30".
	if(isStartDateLastDayOfFebruary || startDateDay == 31) {
		startDateDay = 30;
	}
	if((isEndDateLastDayOfFebruary && !isTreatEndDateAsTerminationDate) || endDateDay == 31) {
		endDateDay = 30;
	}

	return (endDateYear - startDateYear) * 360.0 + (endDateMonth - startDateMonth) * 30.0 + (endDateDay - Math.min(startDateDay, 30.0));
}
 
Example 12
Source File: DayCountConvention_30U_360.java    From finmath-lib with Apache License 2.0 5 votes vote down vote up
@Override
public double getDaycount(final LocalDate startDate, final LocalDate endDate) {
	if(startDate.isAfter(endDate)) {
		return -getDaycount(endDate,startDate);
	}

	int startDateDay 	= startDate.getDayOfMonth();
	final int startDateMonth 	= startDate.getMonthValue();
	final int startDateYear 	= startDate.getYear();

	int endDateDay 		= endDate.getDayOfMonth();
	final int endDateMonth 	= endDate.getMonthValue();
	final int endDateYear 	= endDate.getYear();

	if(
			isEndOfMonth &&
			startDate.getMonth() == Month.FEBRUARY &&
			startDate.getDayOfMonth() == startDate.lengthOfMonth() &&
			endDate.getMonth() == Month.FEBRUARY &&
			endDate.getDayOfMonth() == endDate.lengthOfMonth()
			) {
		endDateDay = 30;
	}

	if(
			isEndOfMonth &&
			startDate.getMonth() == Month.FEBRUARY &&
			startDate.getDayOfMonth() == startDate.lengthOfMonth()
			) {
		startDateDay = 30;
	}

	if(endDateDay > 30 && startDateDay >= 30) {
		endDateDay = 30;
	}
	startDateDay = Math.min(startDateDay,30);

	return (endDateYear - startDateYear) * 360.0 + (endDateMonth - startDateMonth) * 30.0 + (endDateDay - startDateDay);
}
 
Example 13
Source File: ImmutableHolidayCalendar.java    From Strata with Apache License 2.0 5 votes vote down vote up
private Pair<ImmutableSortedSet<LocalDate>, ImmutableSortedSet<LocalDate>> getHolidaysAndWorkingDays() {
  if (startYear == 0) {
    return Pair.of(ImmutableSortedSet.of(), ImmutableSortedSet.of());
  }
  ImmutableSortedSet.Builder<LocalDate> holidays = ImmutableSortedSet.naturalOrder();
  ImmutableSortedSet.Builder<LocalDate> workingDays = ImmutableSortedSet.naturalOrder();
  LocalDate firstOfMonth = LocalDate.of(startYear, 1, 1);
  for (int i = 0; i < lookup.length; i++) {
    int monthData = lookup[i];
    int monthLen = firstOfMonth.lengthOfMonth();
    int dow0 = firstOfMonth.getDayOfWeek().ordinal();
    int bit = 1;
    for (int j = 0; j < monthLen; j++) {
      // if it is a holiday and not a weekend, then add the date
      if ((monthData & bit) == 0 && (weekends & (1 << dow0)) == 0) {
        holidays.add(firstOfMonth.withDayOfMonth(j + 1));
      }
      // if it is a working day and a weekend, then add the date
      if ((monthData & bit) != 0 && (weekends & (1 << dow0)) != 0) {
        workingDays.add(firstOfMonth.withDayOfMonth(j + 1));
      }
      dow0 = (dow0 + 1) % 7;
      bit <<= 1;
    }
    firstOfMonth = firstOfMonth.plusMonths(1);
  }
  return Pair.of(holidays.build(), workingDays.build());
}
 
Example 14
Source File: SingleExecutionTime.java    From cron-utils with Apache License 2.0 5 votes vote down vote up
private TimeNode generateDayCandidatesUsingDoW(final ZonedDateTime reference, final WeekDay mondayDoWValue) {
    final LocalDate date = LocalDate.of(reference.getYear(), reference.getMonthValue(), 1);
    final int lengthOfMonth = date.lengthOfMonth();
    final List<Integer> candidates = createDayOfWeekValueGeneratorInstance(daysOfWeekCronField, reference.getYear(), reference.getMonthValue(), mondayDoWValue)
            .generateCandidates(1, lengthOfMonth)
            .stream().distinct().sorted()
            .collect(Collectors.toList());
    return new TimeNode(candidates);
}
 
Example 15
Source File: SingleExecutionTime.java    From cron-utils with Apache License 2.0 5 votes vote down vote up
private List<Integer> generateDayCandidatesQuestionMarkNotSupportedUsingDoWAndDoM(final int year, final int month, final WeekDay mondayDoWValue) {
    final LocalDate date = LocalDate.of(year, month, 1);
    final int lengthOfMonth = date.lengthOfMonth();
    if (daysOfMonthCronField.getExpression() instanceof Always && daysOfWeekCronField.getExpression() instanceof Always) {
        return createDayOfMonthValueGeneratorInstance(daysOfMonthCronField, year, month)
                .generateCandidates(1, lengthOfMonth)
                .stream().distinct().sorted()
                .collect(Collectors.toList());
    } else if (daysOfMonthCronField.getExpression() instanceof Always) {
        return createDayOfWeekValueGeneratorInstance(daysOfWeekCronField, year, month, mondayDoWValue)
                .generateCandidates(1, lengthOfMonth)
                .stream().distinct().sorted()
                .collect(Collectors.toList());
    } else if (daysOfWeekCronField.getExpression() instanceof Always) {
        return createDayOfMonthValueGeneratorInstance(daysOfMonthCronField, year, month)
                .generateCandidates(1, lengthOfMonth)
                .stream().distinct().sorted()
                .collect(Collectors.toList());
    } else {
        final List<Integer> dayOfWeekCandidates = createDayOfWeekValueGeneratorInstance(daysOfWeekCronField,
                year, month, mondayDoWValue).generateCandidates(1, lengthOfMonth);
        final List<Integer> dayOfMonthCandidates = createDayOfMonthValueGeneratorInstance(daysOfMonthCronField, year, month)
                .generateCandidates(1, lengthOfMonth);
        if (cronDefinition.isMatchDayOfWeekAndDayOfMonth()) {
            final Set<Integer> intersection = new HashSet<>(dayOfWeekCandidates);
            return dayOfMonthCandidates
                    .stream().filter(intersection::contains)
                    .distinct().sorted()
                    .collect(Collectors.toList());
        } else {
            return Stream.concat(dayOfWeekCandidates.stream(), dayOfMonthCandidates.stream())
                    .distinct().sorted()
                    .collect(Collectors.toList());
        }
    }
}
 
Example 16
Source File: OnDayOfMonthValueGenerator.java    From cron-utils with Apache License 2.0 5 votes vote down vote up
private int generateValue(final On on, final int year, final int month) throws NoSuchValueException {
    final int dayOfMonth = on.getTime().getValue();
    switch (on.getSpecialChar().getValue()) {
        case L:
            final int daysBefore = on.getNth().getValue();
            return LocalDate.of(year, month, 1).lengthOfMonth() - (daysBefore > 0 ? daysBefore : 0);
        case W: // First work day of the week
            final LocalDate doM = LocalDate.of(year, month, dayOfMonth);
            if (doM.getDayOfWeek() == DayOfWeek.SATURDAY) { //dayOfWeek is Saturday!
                if (dayOfMonth == 1) { //first day in month is Saturday! We execute on Monday
                    return 3;
                }
                return dayOfMonth - 1;
            }
            if (doM.getDayOfWeek() == DayOfWeek.SUNDAY && (dayOfMonth + 1) <= doM.lengthOfMonth()) {
                return dayOfMonth + 1;
            }
            return dayOfMonth;  // first day of week is a weekday
        case LW:
            final LocalDate lastDayOfMonth = LocalDate.of(year, month, LocalDate.of(year, month, 1).lengthOfMonth());
            final int dow = lastDayOfMonth.getDayOfWeek().getValue();
            final int diff = dow - 5;
            if (diff > 0) {
                return lastDayOfMonth.minusDays(diff).getDayOfMonth();
            }
            return lastDayOfMonth.getDayOfMonth();
        default:
            throw new NoSuchValueException();
    }
}
 
Example 17
Source File: PeriodicSchedule.java    From Strata with Apache License 2.0 4 votes vote down vote up
private static List<LocalDate> generateForwards(
    PeriodicSchedule schedule,
    LocalDate start,
    LocalDate end,
    Frequency frequency,
    RollConvention rollConv,
    StubConvention stubConv,
    boolean explicitInitialStub,
    LocalDate explicitStartDate,
    boolean explicitFinalStub,
    LocalDate explicitEndDate) {

  // validate
  if (rollConv.matches(start) == false) {
    throw new ScheduleException(
        schedule, "Date '{}' does not match roll convention '{}' when starting to roll forwards", start, rollConv);
  }
  // generate
  List<LocalDate> dates = new ArrayList<>(estimateNumberPeriods(start, end, frequency));
  if (explicitInitialStub) {
    dates.add(explicitStartDate);
    dates.add(start);
  } else {
    dates.add(explicitStartDate);
  }
  if (!start.equals(end)) {
    LocalDate temp = rollConv.next(start, frequency);
    while (temp.isBefore(end)) {
      dates.add(temp);
      temp = rollConv.next(temp, frequency);
    }
    // convert short stub to long stub, but only if we actually have a stub
    boolean stub = temp.equals(end) == false;
    if (stub && dates.size() > 1) {
      StubConvention applicableStubConv = stubConv;
      if (stubConv == StubConvention.NONE) {
        // handle edge case where the end date does not follow the EOM rule
        if (rollConv == RollConventions.EOM &&
            frequency.isMonthBased() &&
            !explicitFinalStub &&
            start.getDayOfMonth() == start.lengthOfMonth() &&
            end.getDayOfMonth() == start.getDayOfMonth()) {
          // accept the date and move on using smart rules
          applicableStubConv = StubConvention.SMART_FINAL;
        } else {
          throw new ScheduleException(
              schedule, "Period '{}' to '{}' resulted in a disallowed stub with frequency '{}'", start, end,
              frequency);
        }
      }
      // convert a short stub to a long one if necessary
      if (applicableStubConv.isStubLong(dates.get(dates.size() - 1), end)) {
        dates.remove(dates.size() - 1);
      }
    }
    dates.add(end);
  }
  if (explicitFinalStub) {
    dates.add(explicitEndDate);
  }
  return dates;
}
 
Example 18
Source File: DayRollConventions.java    From Strata with Apache License 2.0 4 votes vote down vote up
@Override
public boolean matches(LocalDate date) {
  ArgChecker.notNull(date, "date");
  return date.getDayOfMonth() == day ||
      (date.getMonthValue() == 2 && day >= date.lengthOfMonth() && date.getDayOfMonth() == date.lengthOfMonth());
}
 
Example 19
Source File: DateTimeExamples.java    From Java8InAction with MIT License 4 votes vote down vote up
private static void useLocalDate() {
    LocalDate date = LocalDate.of(2014, 3, 18);
    int year = date.getYear(); // 2014
    Month month = date.getMonth(); // MARCH
    int day = date.getDayOfMonth(); // 18
    DayOfWeek dow = date.getDayOfWeek(); // TUESDAY
    int len = date.lengthOfMonth(); // 31 (days in March)
    boolean leap = date.isLeapYear(); // false (not a leap year)
    System.out.println(date);

    int y = date.get(ChronoField.YEAR);
    int m = date.get(ChronoField.MONTH_OF_YEAR);
    int d = date.get(ChronoField.DAY_OF_MONTH);

    LocalTime time = LocalTime.of(13, 45, 20); // 13:45:20
    int hour = time.getHour(); // 13
    int minute = time.getMinute(); // 45
    int second = time.getSecond(); // 20
    System.out.println(time);

    LocalDateTime dt1 = LocalDateTime.of(2014, Month.MARCH, 18, 13, 45, 20); // 2014-03-18T13:45
    LocalDateTime dt2 = LocalDateTime.of(date, time);
    LocalDateTime dt3 = date.atTime(13, 45, 20);
    LocalDateTime dt4 = date.atTime(time);
    LocalDateTime dt5 = time.atDate(date);
    System.out.println(dt1);

    LocalDate date1 = dt1.toLocalDate();
    System.out.println(date1);
    LocalTime time1 = dt1.toLocalTime();
    System.out.println(time1);

    Instant instant = Instant.ofEpochSecond(44 * 365 * 86400);
    Instant now = Instant.now();

    Duration d1 = Duration.between(LocalTime.of(13, 45, 10), time);
    Duration d2 = Duration.between(instant, now);
    System.out.println(d1.getSeconds());
    System.out.println(d2.getSeconds());

    Duration threeMinutes = Duration.of(3, ChronoUnit.MINUTES);
    System.out.println(threeMinutes);

    JapaneseDate japaneseDate = JapaneseDate.from(date);
    System.out.println(japaneseDate);
}
 
Example 20
Source File: DaysInMonth.java    From levelup-java-examples with Apache License 2.0 3 votes vote down vote up
@Test
public void days_in_month_java8() {
	
	LocalDate date = LocalDate.of(2014, Month.APRIL, 01);

	int length = date.getMonth().length(true);
	
	assertEquals(30, length);
	
	int length2 = date.lengthOfMonth();
	
	assertEquals(30, length2);		
}