下面列出了java.time.Period#getYears ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
public void difference_between_two_dates_java8_period() {
LocalDate sinceGraduation = LocalDate.of(1984, Month.JUNE, 4);
LocalDate currentDate = LocalDate.now();
Period betweenDates = Period.between(sinceGraduation, currentDate);
int diffInDays = betweenDates.getDays();
int diffInMonths = betweenDates.getMonths();
int diffInYears = betweenDates.getYears();
logger.info(diffInDays);
logger.info(diffInMonths);
logger.info(diffInYears);
assertTrue(diffInDays >= anyInt());
assertTrue(diffInMonths >= anyInt());
assertTrue(diffInYears >= anyInt());
}
public static String formatPeriod(Period value) {
if (value.isZero()) {
return "0 days";
}
String result = "";
int years = value.getYears(), months = value.getMonths(),
days = value.getDays();
if (years != 0) {
result += years + " years ";
}
if (months != 0) {
result += months + " months ";
}
if (days != 0) {
result += days + " days ";
}
return result.trim();
}
public int getLengthOfService(Employee employee, LocalDate refDate) throws AxelorException {
try {
Period period =
Period.between(
employee.getSeniorityDate(),
refDate == null ? Beans.get(AppBaseService.class).getTodayDate() : refDate);
return period.getYears();
} catch (IllegalArgumentException e) {
throw new AxelorException(
e.getCause(),
employee,
TraceBackRepository.CATEGORY_NO_VALUE,
I18n.get(IExceptionMessage.EMPLOYEE_NO_SENIORITY_DATE),
employee.getName());
}
}
public int getAge(Employee employee, LocalDate refDate) throws AxelorException {
try {
Period period =
Period.between(
employee.getBirthDate(),
refDate == null ? Beans.get(AppBaseService.class).getTodayDate() : refDate);
return period.getYears();
} catch (IllegalArgumentException e) {
throw new AxelorException(
e.getCause(),
employee,
TraceBackRepository.CATEGORY_NO_VALUE,
I18n.get(IExceptionMessage.EMPLOYEE_NO_BIRTH_DATE),
employee.getName());
}
}
/**
* Returns a string representation of the amount of time.
* @param value Period to convert to a String
* @return the amount of time in ISO8601 string format
*/
public String toString(Period value) {
final String str;
if (value.isZero()) {
str = "PT0S";
} else {
StringBuilder buf = new StringBuilder();
buf.append('P');
if (value.getYears() != 0) {
buf.append(value.getYears()).append('Y');
}
if (value.getMonths() != 0) {
buf.append(value.getMonths()).append('M');
}
if (value.getDays() != 0) {
buf.append(value.getDays()).append('D');
}
str = buf.toString();
}
return str;
}
private javax.xml.datatype.Duration toYearsMonthDuration(DatatypeFactory datatypeFactory, LocalDate date1, LocalDate date2) {
Period between = Period.between(date2, date1);
int years = between.getYears();
int months = between.getMonths();
if (between.isNegative()) {
years = - years;
months = - months;
}
return datatypeFactory.newDurationYearMonth(!between.isNegative(), years, months);
}
private Duration toYearsMonthDuration(DatatypeFactory datatypeFactory, LocalDate date1, LocalDate date2) {
Period between = Period.between(date2, date1);
int years = between.getYears();
int months = between.getMonths();
if (between.isNegative()) {
years = - years;
months = - months;
}
return datatypeFactory.newDurationYearMonth(!between.isNegative(), years, months);
}
/** Calculate the difference between two dates in years */
private static int yearsDiff(String start, String end) {
LocalDate startDate = yagoToDate(start).toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
LocalDate endDate = yagoToDate(end).toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
Period p = Period.between(startDate, endDate);
return p.getYears();
}
/**
* 获取两个日期的差 field参数为ChronoUnit.*.
*
* @param startTime
* @param endTime
* @param field
* @return long
*/
public static long betweenTwoTime(LocalDateTime startTime, LocalDateTime endTime, ChronoUnit field) {
Period period = Period.between(LocalDate.from(startTime), LocalDate.from(endTime));
if (field == ChronoUnit.YEARS) {
return period.getYears();
}
if (field == ChronoUnit.MONTHS) {
return period.getYears() * 12L + period.getMonths();
}
return field.between(startTime, endTime);
}
@Override
protected void set(PreparedStatement st, Period value, int index, SharedSessionContractImplementor session) throws SQLException {
if (value == null) {
st.setNull(index, Types.OTHER);
} else {
final int days = value.getDays();
final int months = value.getMonths();
final int years = value.getYears();
st.setObject(index, new PGInterval(years, months, days, 0, 0, 0));
}
}
/**
* Returns a person's age in decimal years. (ex. 7.5 ~ 7 years 6 months old)
*
* @param time The time when their age should be calculated.
* @return decimal age in years
*/
public double ageInDecimalYears(long time) {
Period agePeriod = age(time);
double years = agePeriod.getYears() + agePeriod.getMonths() / 12.0
+ agePeriod.getDays() / 365.2425;
if (years < 0) {
years = 0;
}
return years;
}
@Nonnull
@Nonempty
public static String getPeriodText (@Nonnull final LocalDateTime aNowLDT,
@Nonnull final LocalDateTime aNotAfter,
@Nonnull final IPeriodTextProvider aTextProvider)
{
final Period aPeriod = Period.between (aNowLDT.toLocalDate (), aNotAfter.toLocalDate ());
final Duration aDuration = Duration.between (aNowLDT.toLocalTime (), aNotAfter.toLocalTime ());
final int nYears = aPeriod.getYears ();
final int nMonth = aPeriod.getMonths ();
int nDays = aPeriod.getDays ();
long nTotalSecs = aDuration.getSeconds ();
if (nTotalSecs < 0)
{
if (nDays > 0 || nMonth > 0 || nYears > 0)
{
nTotalSecs += CGlobal.SECONDS_PER_DAY;
nDays--;
}
}
final long nHours = nTotalSecs / CGlobal.SECONDS_PER_HOUR;
nTotalSecs -= nHours * CGlobal.SECONDS_PER_HOUR;
final long nMinutes = nTotalSecs / CGlobal.SECONDS_PER_MINUTE;
nTotalSecs -= nMinutes * CGlobal.SECONDS_PER_MINUTE;
return getPeriodText (nYears, nMonth, nDays, nHours, nMinutes, nTotalSecs, aTextProvider);
}
/**
* Converts an FpML 'AdjustedRelativeDateOffset' to a resolved {@code LocalDate}.
*
* @param baseEl the FpML adjustable date element
* @return the resolved date
* @throws RuntimeException if unable to parse
*/
public AdjustableDate parseAdjustedRelativeDateOffset(XmlElement baseEl) {
// FpML content: ('periodMultiplier', 'period', 'dayType?',
// 'businessDayConvention', 'BusinessCentersOrReference.model?'
// 'dateRelativeTo', 'adjustedDate', 'relativeDateAdjustments?')
// The 'adjustedDate' element is ignored
XmlElement relativeToEl = lookupReference(baseEl.getChild("dateRelativeTo"));
LocalDate baseDate;
if (relativeToEl.hasContent()) {
baseDate = parseDate(relativeToEl);
} else if (relativeToEl.getName().contains("relative")) {
baseDate = parseAdjustedRelativeDateOffset(relativeToEl).getUnadjusted();
} else {
throw new FpmlParseException(
"Unable to resolve 'dateRelativeTo' to a date: " + baseEl.getChild("dateRelativeTo").getAttribute(HREF));
}
Period period = parsePeriod(baseEl);
Optional<XmlElement> dayTypeEl = baseEl.findChild("dayType");
boolean calendarDays = period.isZero() || (dayTypeEl.isPresent() && dayTypeEl.get().getContent().equals("Calendar"));
BusinessDayAdjustment bda1 = parseBusinessDayAdjustments(baseEl);
BusinessDayAdjustment bda2 = baseEl.findChild("relativeDateAdjustments")
.map(el -> parseBusinessDayAdjustments(el))
.orElse(bda1);
// interpret and resolve, simple calendar arithmetic or business days
LocalDate resolvedDate;
if (period.getYears() > 0 || period.getMonths() > 0 || calendarDays) {
resolvedDate = bda1.adjust(baseDate.plus(period), refData);
} else {
LocalDate datePlusBusDays = bda1.getCalendar().resolve(refData).shift(baseDate, period.getDays());
resolvedDate = bda1.adjust(datePlusBusDays, refData);
}
return AdjustableDate.of(resolvedDate, bda2);
}
@Override
public void wrap(final Period period) {
this.years = period.getYears();
this.months = period.getMonths();
this.days = period.getDays();
}
public Integer yearDiff(ZonedDateTime dateTime1, ZonedDateTime dateTime2) {
Period period = periodBetween(dateTime1, dateTime2);
return period.getYears();
}
public Integer yearDiff(LocalDate dateTime1, LocalDate dateTime2) {
Period period = periodBetween(dateTime1, dateTime2);
return period.getYears();
}
/** @param amount Relative time span
* @return Legacy specification, e.g. "-3 days -3.124 seconds"
*/
public static String formatAsLegacy(final TemporalAmount amount)
{
final StringBuilder buf = new StringBuilder();
if (amount instanceof Period)
{
final Period period = (Period) amount;
if (period.isZero())
return "now";
if (period.getYears() > 1)
buf.append(-period.getYears()).append(" years ");
if (period.getMonths() > 0)
buf.append(-period.getMonths()).append(" months ");
if (period.getDays() > 0)
buf.append(-period.getDays()).append(" days");
}
else
{
long secs = ((Duration) amount).getSeconds();
if (secs == 0)
return "now";
int p = (int) (secs / (24*60*60));
if (p > 0)
{
buf.append(-p).append(" days ");
secs -= p * (24*60*60);
}
p = (int) (secs / (60*60));
if (p > 0)
{
buf.append(-p).append(" hours ");
secs -= p * (60*60);
}
p = (int) (secs / (60));
if (p > 0)
{
buf.append(-p).append(" minutes ");
secs -= p * (60);
}
final long ms = ((Duration) amount).getNano() / 1000000;
if (ms > 0)
buf.append(-secs - ms / 1000.0).append(" seconds");
else
if (secs > 0)
buf.append(-secs).append(" seconds");
}
return buf.toString().trim();
}
/** Format a temporal amount
*
* @param amount {@link TemporalAmount}
* @return Text like "2 days" that {@link #parseTemporalAmount(String)} can parse
*/
public static String format(final TemporalAmount amount)
{
final StringBuilder buf = new StringBuilder();
if (amount instanceof Period)
{
final Period period = (Period) amount;
if (period.isZero())
return NOW;
if (period.getYears() == 1)
buf.append("1 year ");
else if (period.getYears() > 1)
buf.append(period.getYears()).append(" years ");
if (period.getMonths() == 1)
buf.append("1 month ");
else if (period.getMonths() > 0)
buf.append(period.getMonths()).append(" months ");
if (period.getDays() == 1)
buf.append("1 day");
else if (period.getDays() > 0)
buf.append(period.getDays()).append(" days");
}
else
{
long secs = ((Duration) amount).getSeconds();
if (secs == 0)
return NOW;
int p = (int) (secs / (24*60*60));
if (p > 0)
{
if (p == 1)
buf.append("1 day ");
else
buf.append(p).append(" days ");
secs -= p * (24*60*60);
}
p = (int) (secs / (60*60));
if (p > 0)
{
if (p == 1)
buf.append("1 hour ");
else
buf.append(p).append(" hours ");
secs -= p * (60*60);
}
p = (int) (secs / (60));
if (p > 0)
{
if (p == 1)
buf.append("1 minute ");
else
buf.append(p).append(" minutes ");
secs -= p * (60);
}
if (secs > 0)
if (secs == 1)
buf.append("1 second ");
else
buf.append(secs).append(" seconds ");
final int ms = ((Duration)amount).getNano() / 1000000;
if (ms > 0)
buf.append(ms).append(" ms");
}
return buf.toString().trim();
}
public int getAge(Person person){
Period p = Period.between(person.getDateOfBirth(), LocalDate.now());
return p.getYears();
}
/**
* 获取两个日期的差 field参数为ChronoUnit.*
* @param startTime
* @param endTime
* @param field 单位(年月日时分秒)
* @return
*/
public static long betweenTwoTime(LocalDateTime startTime, LocalDateTime endTime, ChronoUnit field) {
Period period = Period.between(LocalDate.from(startTime), LocalDate.from(endTime));
if (field == ChronoUnit.YEARS) return period.getYears();
if (field == ChronoUnit.MONTHS) return period.getYears() * 12 + period.getMonths();
return field.between(startTime, endTime);
}