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; } }
private String get_interval(DateTime largerDatetime, DateTime smallerDateTime) throws HydraClientException{ int year_diff = Years.yearsBetween(smallerDateTime, largerDatetime).getYears(); int month_diff = Months.monthsBetween(smallerDateTime, largerDatetime).getMonths(); int day_diff = Days.daysBetween(smallerDateTime, largerDatetime).getDays(); int hour_diff = Hours.hoursBetween(smallerDateTime, largerDatetime).getHours(); int min_diff = Minutes.minutesBetween(smallerDateTime, largerDatetime).getMinutes(); if (year_diff > 0){return year_diff+"YEAR";} if (month_diff > 0){return month_diff+"MONTH";} if (day_diff > 0){return day_diff+"DAY";} if (hour_diff > 0){return hour_diff+"HOUR";} if (min_diff > 0){return min_diff+"MIN";} throw new HydraClientException("Could not compute interval between times " + smallerDateTime.toString() + "and" + largerDatetime.toString()); }
/** * 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 public Integer[] transform(final InputRow inputRow) { final Integer[] result = new Integer[2]; final Date date = inputRow.getValue(dateColumn); if (date != null) { final long diffMillis = today.getTime() - date.getTime(); final int diffDays = (int) (diffMillis / (1000 * 60 * 60 * 24)); result[0] = diffDays; // use Joda time to easily calculate the diff in years final int diffYears = Years.yearsBetween(new DateTime(date), new DateTime(today)).getYears(); result[1] = diffYears; } return result; }
@Override 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 Integer[] transform(InputRow inputRow) { Integer[] result = new Integer[2]; Date date = inputRow.getValue(dateColumn); if (date != null) { long diffMillis = today.getTime() - date.getTime(); int diffDays = (int) (diffMillis / (1000 * 60 * 60 * 24)); result[0] = diffDays; // use Joda time to easily calculate the diff in years int diffYears = Years.yearsBetween(new DateTime(date), new DateTime(today)).getYears(); result[1] = diffYears; } return result; }
@Override public Long exec(Tuple input) throws IOException { if (input == null || input.size() < 2) { 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(); }
@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 Integer findDifferenceBetween(Calendar start, Calendar end, String type){ if(type == null || type.trim().isEmpty()){ throw new IllegalArgumentException("You must inform a diff type (MONTHS, YEARS or DAYS)."); } DateTime dtStart = new DateTime(start.getTimeInMillis()); DateTime dtEnd = new DateTime(end.getTimeInMillis()); if(MONTHS.equals(type)){ return Months.monthsBetween(dtStart, dtEnd).getMonths(); } else{ if(YEARS.equals(type)){ return Years.yearsBetween(dtStart, dtEnd).getYears(); } else{ return Days.daysBetween(dtStart, dtEnd).getDays(); } } }
@NonNull public static List getTokenDurationAsStringList(LocalDate expiry, String year, String month, String day) {// Get months LocalDate start = new LocalDate(DateTime.now()); int years = Years.yearsBetween(start, expiry).getYears(); // Subtract this number of years from the end date so we can calculate days expiry = expiry.minusYears(years); int months = Months.monthsBetween(start, expiry).getMonths(); // Subtract this number of months from the end date so we can calculate days expiry = expiry.minusMonths(months); // Get days int days = Days.daysBetween(start, expiry).getDays(); String y = null, m = null, d = null; List list = new ArrayList(); if (years > 0) { y = years + year; list.add(y); } if (months > 0) { m = months + month; list.add(m); } if (days > 0) { d = days + day; list.add(d); } return list; }
@Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_knell); ButterKnife.bind(this); Birthday birthday = getBirthdayManager().get(); DateTime birDateTime = new DateTime(birthday.year, birthday.month, birthday.day, 0, 0); Days days = Days.daysBetween(birDateTime, DateTime.now()); Hours hours = Hours.hoursBetween(birDateTime, DateTime.now()); Minutes minutes = Minutes.minutesBetween(birDateTime, DateTime.now()); Weeks weeks = Weeks.weeksBetween(birDateTime, DateTime.now()); Years years = Years.yearsBetween(birDateTime, DateTime.now()); Months months = Months.monthsBetween(birDateTime, DateTime.now()); Timber.d("onCreate: 年:%d", years.getYears()); Timber.d("onCreate: 月:%d", months.getMonths()); Timber.d("onCreate: 周:%d", weeks.getWeeks()); Timber.d("onCreate: 天数为:%d", days.getDays()); Timber.d("onCreate: 小时数为:%d", hours.getHours()); Timber.d("onCreate: 分钟数为:%d", minutes.getMinutes()); tvYear.setText(String.valueOf(years.getYears())); tvMonth.setText(String.valueOf(months.getMonths())); tvWeek.setText(String.valueOf(weeks.getWeeks())); tvDay.setText(String.valueOf(days.getDays())); tvHour.setText(String.valueOf(hours.getHours())); tvMinute.setText(String.valueOf(minutes.getMinutes())); }
public static DateTime futureDateTime() { DateTime now = DateTime.now(); long min = now.getMillis(); long max = now.plus(Years.TWO).getMillis(); double random = randomDouble(min, max); return new DateTime(Double.valueOf(random).longValue()); }
public static DateTime pastDateTime() { DateTime now = DateTime.now(); long min = now.minus(Years.TWO).getMillis(); long max = now.getMillis(); double random = randomDouble(min, max); return new DateTime(Double.valueOf(random).longValue()); }
public CreditCard(CreditCardNumber number, String cardHolderName, Months expiryMonth, Years expiryYear) { super(); this.number = number; this.cardHolderName = cardHolderName; this.expiryMonth = expiryMonth; this.expiryYear = expiryYear; }
public static ReadablePeriod parsePeriodString(String periodStr) { ReadablePeriod period; char periodUnit = periodStr.charAt(periodStr.length() - 1); if (periodStr.equals("null") || periodUnit == 'n') { return null; } int periodInt = Integer.parseInt(periodStr.substring(0, periodStr.length() - 1)); switch (periodUnit) { case 'y': period = Years.years(periodInt); break; case 'M': period = Months.months(periodInt); break; case 'w': period = Weeks.weeks(periodInt); break; case 'd': period = Days.days(periodInt); break; case 'h': period = Hours.hours(periodInt); break; case 'm': period = Minutes.minutes(periodInt); break; case 's': period = Seconds.seconds(periodInt); break; default: throw new IllegalArgumentException("Invalid schedule period unit '" + periodUnit); } return period; }
public static ChildViewModel fromChild(Child child) { int age = Years.yearsBetween(child.getBirthdate(), LocalDate.now()).getYears(); return ChildViewModel.create( asString(age), asString(child.getBirthdate()), child.getGender().getValue() ); }
public static ChildCareViewModel fromChild(Child child) { int age = Years.yearsBetween(child.getBirthdate(), LocalDate.now()).getYears(); return ChildCareViewModel.create( child.getName(), 0 ); }
@Override public IntervalWindow assignWindow(Instant timestamp) { DateTime datetime = new DateTime(timestamp, timeZone); DateTime offsetStart = startDate.withMonthOfYear(monthOfYear).withDayOfMonth(dayOfMonth); int yearOffset = Years.yearsBetween(offsetStart, datetime).getYears() / number * number; DateTime begin = offsetStart.plusYears(yearOffset); DateTime end = begin.plusYears(number); return new IntervalWindow(begin.toInstant(), end.toInstant()); }
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; }
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)); } }
private static String toYears(DateTime date, DateTime now) { int result = Years.yearsBetween(date, now).getYears(); if (Math.abs(result) >= 1) { return Math.abs(result) == 1 ? (result == 1 ? "Last" : "Next") + " year" : toReference(Math.abs(result), result, " years "); } return null; }
@Override public Integer getAge() { if (this.birthDateValue != null && !isSuppressPersonal()) { DateTime endDate; if (this.deceasedDateValue != null) { endDate = new DateTime(this.deceasedDateValue); } else { endDate = new DateTime(); } return Years.yearsBetween(new DateTime(this.birthDateValue), endDate).getYears(); } return null; }
/** * 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()); }
public LocalDateTime resolve(LocalDateTime base) { if (this.duration==null || this.durationUnit==null) { return null; } ReadablePeriod period = null; if (DAYS.equals(durationUnit)) { period = Days.days(getDurationAsInt()); } else if (WEEKS.equals(durationUnit)) { period = Weeks.weeks(getDurationAsInt()); } else if (HOURS.equals(durationUnit)) { period = Hours.hours(getDurationAsInt()); } else if (MONTHS.equals(durationUnit)) { period = Months.months(getDurationAsInt()); } else if (YEARS.equals(durationUnit)) { period = Years.years(getDurationAsInt()); } else if (MINUTES.equals(durationUnit)) { period = Minutes.minutes(getDurationAsInt()); } else { return null; } LocalDateTime time = base.plus(period); if (atHour!=null) { LocalDateTime atTime = time.withTime(atHour, atMinute!=null ? atMinute : 0, 0, 0); if (atTime.isBefore(time)) { time = atTime.plusDays(1); } else { time = atTime; } } else if (isDayResolutionOrBigger()) { time = time.withTime(23, 59, 59, 999); } return time; }
public Integer getAge() { if (this.birthDay != null) { DateTime start = new DateTime(this.birthDay); DateTime end = DateTime.now(); return Years.yearsBetween(start.toLocalDate(), end.toLocalDate()). getYears(); } return null; }
public Integer getAge() { DateTime now = new DateTime(); if (birthDate == null){ return null; } return Years.yearsBetween(birthDate, now).getYears(); }
private void calcAge() { DateTime birthDateValue = new DateTime(birthDate.getValue()); int ageValue = Years.yearsBetween(birthDateValue, DateTime.now()).getYears(); age.setReadOnly(false); age.setConvertedValue(ageValue); age.setReadOnly(true); }
/** * 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); }
public int getLengthOfService(Employee employee, LocalDate refDate) throws AxelorException{ try{ Years years = Years.yearsBetween(employee.getSeniorityDate(), refDate == null ? Beans.get(GeneralService.class).getTodayDate() : refDate ); return years.getYears(); }catch (IllegalArgumentException e){ throw new AxelorException(String.format( I18n.get( IExceptionMessage.EMPLOYEE_NO_SENIORITY_DATE ), employee.getName() ), IException.NO_VALUE); } }
public int getAge(Employee employee, LocalDate refDate) throws AxelorException{ try{ Years years = Years.yearsBetween(employee.getBirthDate(), refDate == null ? Beans.get(GeneralService.class).getTodayDate() : refDate ); return years.getYears(); }catch (IllegalArgumentException e){ throw new AxelorException(String.format( I18n.get( IExceptionMessage.EMPLOYEE_NO_BIRTH_DATE ), employee.getName() ), IException.NO_VALUE); } }
/** * @see Marvel#getSeries(String, String, String, String, org.joda.time.Years, org.joda.time.DateTime, int[], int[], int[], int[], int[], String, int, int) */ public ApiReturn<Series> getSeries( String seriesType, String contains, String title, String titleStartsWith, Years startYear, DateTime modifiedSince, int[] comics, int[] stories, int[] events, int[] creators, int[] characters, String orderBy, int limit, int offset ) { ImmutableMap.Builder<String, Object> additional = ImmutableMap.builder(); if( !isNullOrEmpty( seriesType )) additional.put( MarvelConstants.query_seriesType, seriesType ); if( !isNullOrEmpty( contains )) additional.put( MarvelConstants.query_contains, contains ); if( !isNullOrEmpty( title )) additional.put( MarvelConstants.query_title, title ); if( !isNullOrEmpty( titleStartsWith )) additional.put( MarvelConstants.query_titleStartsWith, titleStartsWith ); if( startYear != null ) additional.put( MarvelConstants.query_startYear, startYear.toString() ); Map<String, Object> params = collectCommonQueryParams( additional, modifiedSince, orderBy, limit, offset, comics, null, events, stories, characters, creators, null, null ); WebTarget t = getTarget(params, MarvelConstants.path_series); return call( t, new GenericType<ApiReturn<Series>>(){}); }