下面列出了java.time.Period#getDays ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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();
}
private void updateExpectedDeletion(LocalDateTime expectedRemovalDate) {
expectedDeletion.getStyleClass().clear();
expectedRemovalText.setValue("");
if (expectedRemovalDate == null) {
return;
}
LocalDate today = LocalDate.now();
Period timeUntilDeletion = today.until(expectedRemovalDate.toLocalDate());
int daysUntilDeletion = timeUntilDeletion.getDays();
if (daysUntilDeletion < 1) {
expectedRemovalText.setValue("Will be removed today");
expectedDeletion.getStyleClass().add("removing-today");
} else if (daysUntilDeletion < 2) {
expectedRemovalText.setValue("Will be removed tomorrow");
expectedDeletion.getStyleClass().add("removing-today");
} else if (daysUntilDeletion < 7) {
expectedRemovalText.setValue(String.format("Will be removed in %d days", daysUntilDeletion));
expectedDeletion.getStyleClass().add("removing-soon");
}
}
/**
* 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;
}
@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());
}
@Override
public final String apply(Period input) {
if (input == null) {
final Supplier<String> nullValue = getNullValue();
return nullValue != null ? nullValue.get() : "null";
} else {
final int days = input.getDays();
return days + "D";
}
}
@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);
}
/**
* 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(), "Frequency period must not be zero");
ArgChecker.isFalse(period.isNegative(), "Frequency period must not be negative");
this.period = period;
this.name = name;
// calculate events per year
long monthsLong = period.toTotalMonths();
if (monthsLong > MAX_MONTHS) {
eventsPerYear = 0;
eventsPerYearEstimate = 0;
} else {
int months = (int) monthsLong;
int days = period.getDays();
if (months > 0 && days == 0) {
eventsPerYear = (12 % months == 0) ? 12 / months : -1;
eventsPerYearEstimate = 12d / months;
} else if (days > 0 && months == 0) {
eventsPerYear = (364 % days == 0) ? 364 / days : -1;
eventsPerYearEstimate = 364d / days;
} else {
eventsPerYear = -1;
double estimatedSecs = months * MONTHS.getDuration().getSeconds() + days * DAYS.getDuration().getSeconds();
eventsPerYearEstimate = YEARS.getDuration().getSeconds() / estimatedSecs;
}
}
}
public PeriodHandle(Period o) {
this.years = o.getYears();
this.months = o.getMonths();
this.days = o.getDays();
}
@Override
public void wrap(final Period period) {
this.years = period.getYears();
this.months = period.getMonths();
this.days = period.getDays();
}
/** @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();
}
/**
* Obtains an instance 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);
}
/**
* Obtains an instance 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.
*
* @param period the period to convert to a tenor
* @return the tenor
* @throws IllegalArgumentException if the period is negative or zero
*/
public static Tenor of(Period period) {
int days = period.getDays();
long months = period.toTotalMonths();
if (months == 0 && days != 0) {
return ofDays(days);
}
return new Tenor(period, period.toString().substring(1));
}