下面列出了怎么用org.joda.time.Years的API类实例代码及写法,或者点击链接到github查看源代码。
protected static int dateDiff(Date beginDate, Date endDate, DateType type) {
//Interval interval = new Interval(beginDate.getTime(), endDate.getTime());
//Period p = interval.toPeriod();
DateTime start =new DateTime(beginDate);
DateTime end =new DateTime(endDate);
if (DateType.YEAR.equals(endDate)) {
return Years.yearsBetween(start, end).getYears();
} else if (DateType.MONTH.equals(type)) {
return Months.monthsBetween(start, end).getMonths();
} else if (DateType.WEEK.equals(type)) {
return Weeks.weeksBetween(start, end).getWeeks();
} else if (DateType.DAY.equals(type)) {
return Days.daysBetween(start, end).getDays();
} else if (DateType.HOUR.equals(type)) {
return Hours.hoursBetween(start, end).getHours();
} else if (DateType.MINUTE.equals(type)) {
return Minutes.minutesBetween(start, end).getMinutes();
} else if (DateType.SECOND.equals(type)) {
return Seconds.secondsBetween(start, end).getSeconds();
} else {
return 0;
}
}
/***
*
* @param time 传入当前计算的日期毫秒数
* @param maxYears 设置加权因子的最大年份上限
* @return 该日期的一个动态加权评分
*/
public static float getYearScore(long time,int maxYears){
if(time==0){//没有日期的数据,不做加权操作
return 1;
}
DateTime now=new DateTime();
DateTime varTime=new DateTime(time);
int year= Years.yearsBetween(varTime,now).getYears();
float score=1;
if(year>0&&year<=maxYears){
return year*score;
}else if(year>maxYears){ //超过上限者,统一按上限值乘以1.5倍算
return score*maxYears*1.5f;
}
return score;
}
/**
* Returns the number of years between two dates.
*/
@Function("YEARS")
@FunctionParameters({
@FunctionParameter("startDate"),
@FunctionParameter("endDate")})
public Integer YEARS(Object startDate, Object endDate){
Date startDateObj = convertDateObject(startDate);
if(startDateObj==null) {
logCannotConvertToDate();
return null;
}
Date endDateObj = convertDateObject(endDate);
if(endDateObj==null){
logCannotConvertToDate();
return null;
}
else{
LocalDate dt1=new LocalDate(startDateObj);
LocalDate dt2=new LocalDate(endDateObj);
return Years.yearsBetween(dt1, dt2).getYears();
}
}
@Override
protected String formatDate(DateTime now, DateTime then) {
if (dateFormat == null)
buildDateFormat();
StringBuilder builder = new StringBuilder();
if (hasFormat(WEEKDAY) && now.get(omitWeekday) == then.get(omitWeekday))
builder.append(weekdayFormat.print(then));
if (hasFormat(DAYS | MONTHS)) {
if (builder.length() > 0)
builder.append(", ");
builder.append(dateFormat.print(then));
}
if (hasFormat(YEARS) && Years.yearsBetween(now, then).getYears() != 0)
builder.append(yearFormat.print(then));
if (hasFormat(TIME) && now.get(omitTime) == then.get(omitTime)) {
builder.append(", ");
builder.append(formatTime(now, then));
}
return builder.toString();
}
@Override
@SuppressWarnings("EqualsBetweenInconvertibleTypes") // SpecimenType knows how to do equals(Class<?>)
public Object create(Object request, SpecimenContext context) {
if (!(request instanceof SpecimenType)) {
return new NoSpecimen();
}
SpecimenType type = (SpecimenType) request;
if (!BaseSingleFieldPeriod.class.isAssignableFrom(type.getRawType())) {
return new NoSpecimen();
}
Duration duration = (Duration) context.resolve(Duration.class);
if (type.equals(Seconds.class)) return Seconds.seconds(Math.max(1, (int) duration.getStandardSeconds()));
if (type.equals(Minutes.class)) return Minutes.minutes(Math.max(1, (int) duration.getStandardMinutes()));
if (type.equals(Hours.class)) return Hours.hours(Math.max(1, (int) duration.getStandardHours()));
if (type.equals(Days.class)) return Days.days(Math.max(1, (int) duration.getStandardDays()));
if (type.equals(Weeks.class)) return Weeks.weeks(Math.max(1, (int) duration.getStandardDays() / 7));
if (type.equals(Months.class)) return Months.months(Math.max(1, (int) duration.getStandardDays() / 30));
if (type.equals(Years.class)) return Years.years(Math.max(1, (int) duration.getStandardDays() / 365));
return new NoSpecimen();
}
@Override
public Long exec(Tuple input) throws IOException
{
if (input == null || input.size() < 2 || input.get(0) == null || input.get(1) == null) {
return null;
}
DateTime startDate = (DateTime) input.get(0);
DateTime endDate = (DateTime) input.get(1);
// Larger value first
Years y = Years.yearsBetween(endDate, startDate);
// joda limitation, only integer range, at the risk of overflow, need to be improved
return (long) y.getYears();
}
public static int getYearsBetween(final String date1, final String date2, String format){
try {
final DateTimeFormatter fmt =
DateTimeFormat
.forPattern(format)
.withChronology(
LenientChronology.getInstance(
GregorianChronology.getInstance()));
return Years.yearsBetween(
fmt.parseDateTime(date1),
fmt.parseDateTime(date2)
).getYears();
} catch (Exception ex) {
ex.printStackTrace();
return 0;
}
}
public CreditCard(CreditCardNumber number, String cardHolderName, Months expiryMonth, Years expiryYear) {
super();
this.number = number;
this.cardHolderName = cardHolderName;
this.expiryMonth = expiryMonth;
this.expiryYear = expiryYear;
}
private void formatYears(DateTime now, DateTime then, StringBuffer text) {
int yearsBetween = Years.yearsBetween(now.toLocalDate(), then.toLocalDate()).getYears();
if (yearsBetween == 0) {
if ((format & MONTHS) != 0) {
formatMonths(now, then, text);
} else {
text.append(context.getString(R.string.thisYear));
}
} else if (yearsBetween > 0) { // in N years
text.append(context.getResources().getQuantityString(R.plurals.carbon_inYears, yearsBetween, yearsBetween));
} else { // N years ago
text.append(context.getResources().getQuantityString(R.plurals.carbon_yearsAgo, -yearsBetween, -yearsBetween));
}
}
public static int getTimeSteps(int tempRes, int startTime, int endTime) {
if (startTime > endTime) {
return 0;
}
int timeSteps = 0;
DateTime start = new DateTime(((long)startTime)*1000, DateTimeZone.UTC);
DateTime end = new DateTime(((long)endTime)*1000, DateTimeZone.UTC);
switch(tempRes) {
case FrameworkUtils.HOUR:
timeSteps = Hours.hoursBetween(start, end).getHours();
break;
case FrameworkUtils.DAY:
timeSteps = Days.daysBetween(start, end).getDays();
break;
case FrameworkUtils.WEEK:
timeSteps = Weeks.weeksBetween(start, end).getWeeks();
break;
case FrameworkUtils.MONTH:
timeSteps = Months.monthsBetween(start, end).getMonths();
break;
case FrameworkUtils.YEAR:
timeSteps = Years.yearsBetween(start, end).getYears();
break;
default:
timeSteps = Hours.hoursBetween(start, end).getHours();
break;
}
timeSteps++;
return timeSteps;
}
public static int getDeltaSinceEpoch(int time, int tempRes) {
int delta = 0;
// Epoch
MutableDateTime epoch = new MutableDateTime();
epoch.setDate(0);
DateTime dt = new DateTime(time*1000, DateTimeZone.UTC);
switch(tempRes) {
case FrameworkUtils.HOUR:
Hours hours = Hours.hoursBetween(epoch, dt);
delta = hours.getHours();
break;
case FrameworkUtils.DAY:
Days days = Days.daysBetween(epoch, dt);
delta = days.getDays();
break;
case FrameworkUtils.WEEK:
Weeks weeks = Weeks.weeksBetween(epoch, dt);
delta = weeks.getWeeks();
break;
case FrameworkUtils.MONTH:
Months months = Months.monthsBetween(epoch, dt);
delta = months.getMonths();
break;
case FrameworkUtils.YEAR:
Years years = Years.yearsBetween(epoch, dt);
delta = years.getYears();
break;
default:
hours = Hours.hoursBetween(epoch, dt);
delta = hours.getHours();
break;
}
return delta;
}
public static Integer yearsBetween(String start, String end) {
if (isEmpty(start) || isEmpty(end)) {
return 0;
}
DateTime startDate = new DateTime(start);
DateTime endDate = new DateTime(end);
return Years.yearsBetween(startDate.withDayOfMonth(1).withMonthOfYear(1), endDate.withDayOfMonth(1)
.withMonthOfYear(1)).getYears();
}
public Integer getAge() {
DateTime now = new DateTime();
if (birthDate == null){
return null;
}
return Years.yearsBetween(birthDate, now).getYears();
}
@TLFunctionAnnotation("Returns the difference between dates")
public static final Long dateDiff(TLFunctionCallContext context, Date lhs, Date rhs, DateFieldEnum unit) {
if (unit == DateFieldEnum.MILLISEC) { // CL-1087
return lhs.getTime() - rhs.getTime();
}
long diff = 0;
switch (unit) {
case SECOND:
// we have the difference in seconds
diff = (long) Seconds.secondsBetween(new DateTime(rhs.getTime()), new DateTime(lhs.getTime())).getSeconds();
break;
case MINUTE:
// how many minutes'
diff = (long) Minutes.minutesBetween(new DateTime(rhs.getTime()), new DateTime(lhs.getTime())).getMinutes();
break;
case HOUR:
diff = (long) Hours.hoursBetween(new DateTime(rhs.getTime()), new DateTime(lhs.getTime())).getHours();
break;
case DAY:
// how many days is the difference
diff = (long) Days.daysBetween(new DateTime(rhs.getTime()), new DateTime(lhs.getTime())).getDays();
break;
case WEEK:
// how many weeks
diff = (long) Weeks.weeksBetween(new DateTime(rhs.getTime()), new DateTime(lhs.getTime())).getWeeks();
break;
case MONTH:
diff = (long) Months.monthsBetween(new DateTime(rhs.getTime()), new DateTime(lhs.getTime())).getMonths();
break;
case YEAR:
diff = (long) Years.yearsBetween(new DateTime(rhs.getTime()), new DateTime(lhs.getTime())).getYears();
break;
default:
throw new TransformLangExecutorRuntimeException("Unknown time unit " + unit);
}
return diff;
}
/**
* Calculates the difference between two times, given as long values, and
* returns the period between them in the specified <code>units</code>. The
* units value must be one of:
* <pre>
* {@link #MILLISECONDS}
* {@link #SECONDS}
* {@link #MINUTES}
* {@link #HOURS}
* {@link #DAYS}
* {@link #WEEKS}
* {@link #MONTHS}
* {@link #YEARS}
* </pre>
* All values will be returned as the absolute value of the difference.
*
* @param arg1 The value to use as the minuend.
* @param arg2 The value to use as the subtrahend.
* @param units The time units to use for expressing the difference.
* @return The long value of the difference between the arguments in the
* specified units.
*/
public static long period(long arg1, long arg2, int units) {
long delta = arg1 - arg2;
DateTime start = new DateTime(arg1);
DateTime end = new DateTime(arg2);
// Compute delta into appropriate units
switch (units) {
case YEARS:
delta = Years.yearsBetween(start, end).getYears();
break;
case MONTHS:
delta = Months.monthsBetween(start, end).getMonths();
break;
case WEEKS:
delta = Weeks.weeksBetween(start, end).getWeeks();
break;
case DAYS:
delta = Days.daysBetween(start, end).getDays();
break;
case HOURS:
delta = Hours.hoursBetween(start, end).getHours();
break;
case MINUTES:
delta = Minutes.minutesBetween(start, end).getMinutes();
break;
case SECONDS:
delta = Double.valueOf(Math.floor(delta / 1000.0)).longValue();
break;
case MILLISECONDS:
// Here for completeness but already calculated
break;
default:
throw new IllegalArgumentException("Invalid units: "
+ units + " See Functions.difference(Calendar,Calendar)"
+ " for allowed values");
}
return Math.abs(delta);
}
/**
* Tests that performing a named search automatically saves the last search criteria as well as named search
*/
@Test public void testNamedDocSearchPersistence() throws Exception {
Person user = KimApiServiceLocator.getPersonService().getPersonByPrincipalName("bmcgough");
Collection<UserOptions> allUserOptions_before = userOptionsService.findByWorkflowUser(user.getPrincipalId());
List<UserOptions> namedSearches_before = userOptionsService.findByUserQualified(user.getPrincipalId(), "DocSearch.NamedSearch.%");
DocumentSearchCriteria.Builder criteria = DocumentSearchCriteria.Builder.create();
criteria.setTitle("*IN");
criteria.setSaveName("bytitle");
criteria.setDateCreatedFrom(DateTime.now().minus(Years.ONE)); // otherwise one is set for us
DocumentSearchCriteria c1 = criteria.build();
DocumentSearchResults results = docSearchService.lookupDocuments(user.getPrincipalId(), c1);
Collection<UserOptions> allUserOptions_after = userOptionsService.findByWorkflowUser(user.getPrincipalId());
List<UserOptions> namedSearches_after = userOptionsService.findByUserQualified(user.getPrincipalId(), "DocSearch.NamedSearch.%");
assertEquals(allUserOptions_before.size() + 1, allUserOptions_after.size());
assertEquals(namedSearches_before.size() + 1, namedSearches_after.size());
assertEquals(marshall(c1), userOptionsService.findByOptionId("DocSearch.NamedSearch." + criteria.getSaveName(), user.getPrincipalId()).getOptionVal());
// second search
criteria = DocumentSearchCriteria.Builder.create();
criteria.setTitle("*IN");
criteria.setSaveName("bytitle2");
criteria.setDateCreatedFrom(DateTime.now().minus(Years.ONE)); // otherwise one is set for us
DocumentSearchCriteria c2 = criteria.build();
results = docSearchService.lookupDocuments(user.getPrincipalId(), c2);
allUserOptions_after = userOptionsService.findByWorkflowUser(user.getPrincipalId());
namedSearches_after = userOptionsService.findByUserQualified(user.getPrincipalId(), "DocSearch.NamedSearch.%");
// saves a second named search
assertEquals(allUserOptions_before.size() + 2, allUserOptions_after.size());
assertEquals(namedSearches_before.size() + 2, namedSearches_after.size());
assertEquals(marshall(c2), userOptionsService.findByOptionId("DocSearch.NamedSearch." + criteria.getSaveName(), user.getPrincipalId()).getOptionVal());
}
/**
* Protected setter to allow binding the expiration date.
*
* @param date
*/
protected void setExpirationDate(LocalDate date) {
this.expiryYear = Years.years(date.getYear());
this.expiryMonth = Months.months(date.getMonthOfYear());
}
public static int getYearsBetween(String startDate, String endDate) {
DateTime s = new DateTime( startDate.length()==4 ? startDate + "-01-01" : getStrYMD(startDate.replaceAll("/", "-"), "-") );
DateTime e = new DateTime( endDate.length()==4 ? endDate + "-01-01" : getStrYMD(endDate.replaceAll("/", "-"), "-") );
return Years.yearsBetween(s, e).getYears();
}
@Test
public void creates_instance_of_Years() {
Years years = fixture.create(Years.class);
assertThat(years, notNullValue());
assertThat(years, is(Years.years(1)));
}
protected final void onDefaultSelectorChecked(boolean isChecked) {
mDatePicker.updateDate(mDate.getYear(), mDate.getMonthOfYear(), mDate.getDayOfMonth());
int age = Years.yearsBetween(mDate, LocalDate.now()).getYears();
mSpinner.setSelection(age);
mSwitcher.showNext();
}
public void init(LocalDate date, DatePicker.OnDateChangedListener mListener) {
mDatePicker.init(date.getYear(), date.getMonthOfYear(), date.getDayOfMonth(), mListener);
int age = Years.yearsBetween(date, LocalDate.now()).getYears();
mSpinner.setSelection(age);
}
public void updateDate(int year, int month, int day) {
mDatePicker.updateDate(mDate.getYear(), mDate.getMonthOfYear(), mDate.getDayOfMonth());
int age = Years.yearsBetween(mDate, LocalDate.now()).getYears();
mSpinner.setSelection(age);
}
/**
* Tests that performing a search automatically saves the last search criteria
*/
@Test public void testUnnamedDocSearchPersistence() throws Exception {
Person user = KimApiServiceLocator.getPersonService().getPersonByPrincipalName("bmcgough");
Collection<UserOptions> allUserOptions_before = userOptionsService.findByWorkflowUser(user.getPrincipalId());
List<UserOptions> namedSearches_before = userOptionsService.findByUserQualified(user.getPrincipalId(), "DocSearch.NamedSearch.%");
assertEquals(0, namedSearches_before.size());
assertEquals(0, allUserOptions_before.size());
DocumentSearchCriteria.Builder criteria = DocumentSearchCriteria.Builder.create();
criteria.setTitle("*IN");
criteria.setDateCreatedFrom(DateTime.now().minus(Years.ONE)); // otherwise one is set for us
DocumentSearchCriteria c1 = criteria.build();
DocumentSearchResults results = docSearchService.lookupDocuments(user.getPrincipalId(), c1, true);
Collection<UserOptions> allUserOptions_after = userOptionsService.findByWorkflowUser(user.getPrincipalId());
List<UserOptions> namedSearches_after = userOptionsService.findByUserQualified(user.getPrincipalId(), "DocSearch.NamedSearch.%");
// saves the "last doc search criteria"
// and a pointer to the "last doc search criteria"
assertEquals(allUserOptions_before.size() + 2, allUserOptions_after.size());
assertEquals(namedSearches_before.size(), namedSearches_after.size());
assertEquals("DocSearch.LastSearch.Holding0", userOptionsService.findByOptionId("DocSearch.LastSearch.Order".toString(), user.getPrincipalId()).getOptionVal());
assertEquals(marshall(c1), userOptionsService.findByOptionId("DocSearch.LastSearch.Holding0", user.getPrincipalId()).getOptionVal());
// 2nd search
criteria = DocumentSearchCriteria.Builder.create();
criteria.setTitle("*IN-CFSG*");
criteria.setDateCreatedFrom(DateTime.now().minus(Years.ONE)); // otherwise one is set for us
DocumentSearchCriteria c2 = criteria.build();
results = docSearchService.lookupDocuments(user.getPrincipalId(), c2, true);
// still only 2 more user options
assertEquals(allUserOptions_before.size() + 2, allUserOptions_after.size());
assertEquals(namedSearches_before.size(), namedSearches_after.size());
assertEquals("DocSearch.LastSearch.Holding1,DocSearch.LastSearch.Holding0", userOptionsService.findByOptionId("DocSearch.LastSearch.Order", user.getPrincipalId()).getOptionVal());
assertEquals(marshall(c1), userOptionsService.findByOptionId("DocSearch.LastSearch.Holding0", user.getPrincipalId()).getOptionVal());
assertEquals(marshall(c2), userOptionsService.findByOptionId("DocSearch.LastSearch.Holding1", user.getPrincipalId()).getOptionVal());
}
@Override
public Years fromNonNullString(String s) {
return Years.years(Integer.parseInt(s));
}
@Override
public Years fromNonNullValue(Integer value) {
return Years.years(value);
}
@Override
public String toNonNullString(Years value) {
return "" + value.getYears();
}
@Override
public Integer toNonNullValue(Years value) {
return value.getYears();
}
@Override
public Years fromNonNullValue(String value) {
return Years.years(YEAR_FORMATTER.parseDateTime(value).getYear());
}
@Override
public String toNonNullValue(Years value) {
return YEAR_FORMATTER.print(value.getYears());
}
public Years getYear() {
return year;
}