org.joda.time.Years Java Examples

The following examples show how to use org.joda.time.Years. 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: ScoreTools.java    From solr-custom-score with Apache License 2.0 6 votes vote down vote up
/***
 *
 * @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;

}
 
Example #2
Source File: Interval.java    From program-ab with GNU Lesser General Public License v3.0 6 votes vote down vote up
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;
    }
}
 
Example #3
Source File: DateTimeFunctions.java    From jasperreports with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 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();
	}
}
 
Example #4
Source File: YearsBetween.java    From spork with Apache License 2.0 6 votes vote down vote up
@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();

}
 
Example #5
Source File: AbsoluteDateFormat.java    From NaturalDateFormat with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example #6
Source File: DatetimeUtil.java    From stategen with GNU Affero General Public License v3.0 6 votes vote down vote up
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;
    }
}
 
Example #7
Source File: BaseSingleFieldPeriodRelay.java    From jfixture with MIT License 6 votes vote down vote up
@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();
}
 
Example #8
Source File: Functions.java    From sana.mobile with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * 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);
}
 
Example #9
Source File: DocumentSearchTest.java    From rice with Educational Community License v2.0 5 votes vote down vote up
/**
 * 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());

}
 
Example #10
Source File: DateLib.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 5 votes vote down vote up
@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;
}
 
Example #11
Source File: User.java    From mamute with Apache License 2.0 5 votes vote down vote up
public Integer getAge() {
	DateTime now = new DateTime();
	if (birthDate == null){
		return null;
	}
	return Years.yearsBetween(birthDate, now).getYears();
}
 
Example #12
Source File: ExpressionFunctions.java    From dhis2-android-sdk with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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();
}
 
Example #13
Source File: FrameworkUtils.java    From data-polygamy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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;
}
 
Example #14
Source File: FrameworkUtils.java    From data-polygamy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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;
}
 
Example #15
Source File: CreditCard.java    From micro-ecommerce with Apache License 2.0 5 votes vote down vote up
public CreditCard(CreditCardNumber number, String cardHolderName, Months expiryMonth, Years expiryYear) {
	super();
	this.number = number;
	this.cardHolderName = cardHolderName;
	this.expiryMonth = expiryMonth;
	this.expiryYear = expiryYear;
}
 
Example #16
Source File: RelativeDateFormat.java    From NaturalDateFormat with Apache License 2.0 5 votes vote down vote up
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));
    }
}
 
Example #17
Source File: CreditCard.java    From micro-ecommerce with Apache License 2.0 4 votes vote down vote up
/**
 * 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());
}
 
Example #18
Source File: AgeCalculator.java    From tutorials with MIT License 4 votes vote down vote up
public int calculateAgeWithJodaTime(org.joda.time.LocalDate birthDate, org.joda.time.LocalDate currentDate) {
    // validate inputs ...
    Years age = Years.yearsBetween(birthDate, currentDate);
    return age.getYears();
}
 
Example #19
Source File: YearsHolder.java    From jadira with Apache License 2.0 4 votes vote down vote up
public void setYear(Years year) {
    this.year = year;
}
 
Example #20
Source File: YearsHolder.java    From jadira with Apache License 2.0 4 votes vote down vote up
public Years getYear() {
    return year;
}
 
Example #21
Source File: StringColumnYearsMapper.java    From jadira with Apache License 2.0 4 votes vote down vote up
@Override
public String toNonNullValue(Years value) {
    return YEAR_FORMATTER.print(value.getYears());
}
 
Example #22
Source File: StringColumnYearsMapper.java    From jadira with Apache License 2.0 4 votes vote down vote up
@Override
public Years fromNonNullValue(String value) {
    return Years.years(YEAR_FORMATTER.parseDateTime(value).getYear());
}
 
Example #23
Source File: IntegerColumnYearsMapper.java    From jadira with Apache License 2.0 4 votes vote down vote up
@Override
public Integer toNonNullValue(Years value) {
    return value.getYears();
}
 
Example #24
Source File: IntegerColumnYearsMapper.java    From jadira with Apache License 2.0 4 votes vote down vote up
@Override
public String toNonNullString(Years value) {
    return "" + value.getYears();
}
 
Example #25
Source File: IntegerColumnYearsMapper.java    From jadira with Apache License 2.0 4 votes vote down vote up
@Override
public Years fromNonNullValue(Integer value) {
    return Years.years(value);
}
 
Example #26
Source File: IntegerColumnYearsMapper.java    From jadira with Apache License 2.0 4 votes vote down vote up
@Override
public Years fromNonNullString(String s) {
    return Years.years(Integer.parseInt(s));
}
 
Example #27
Source File: SimpleUtils.java    From bamboobsc with Apache License 2.0 4 votes vote down vote up
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();
}
 
Example #28
Source File: DocumentSearchTest.java    From rice with Educational Community License v2.0 4 votes vote down vote up
/**
 * 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());
}
 
Example #29
Source File: DateOfBirthWidget.java    From sana.mobile with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
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);
}
 
Example #30
Source File: DateOfBirthWidget.java    From sana.mobile with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
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);
}