org.joda.time.Weeks Java Examples

The following examples show how to use org.joda.time.Weeks. 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: 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 #2
Source File: DateTimeFunctions.java    From jasperreports with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Returns the number of weeks between two dates.
 */
@Function("WEEKS")
@FunctionParameters({
	@FunctionParameter("startDate"),
	@FunctionParameter("endDate")})
public Integer WEEKS(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 Weeks.weeksBetween(dt1, dt2).getWeeks();
	}
}
 
Example #3
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 #4
Source File: CalendarUtil.java    From NCalendar with Apache License 2.0 5 votes vote down vote up
/**
 * 获得两个日期距离几周
 *
 * @param date1
 * @param date2
 * @param type  一周
 * @return
 */
public static int getIntervalWeek(LocalDate date1, LocalDate date2, int type) {

    if (type == Attrs.MONDAY) {
        date1 = getMonFirstDayOfWeek(date1);
        date2 = getMonFirstDayOfWeek(date2);
    } else {
        date1 = getSunFirstDayOfWeek(date1);
        date2 = getSunFirstDayOfWeek(date2);
    }

    return Weeks.weeksBetween(date1, date2).getWeeks();

}
 
Example #5
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 #6
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 #7
Source File: Lesson.java    From fenixedu-academic with GNU Lesser General Public License v3.0 5 votes vote down vote up
public String getOccurrenceWeeksAsString() {
    final SortedSet<Integer> weeks = new TreeSet<Integer>();

    final ExecutionCourse executionCourse = getExecutionCourse();
    final YearMonthDay firstPossibleLessonDay = executionCourse.getMaxLessonsPeriod().getLeft();
    final YearMonthDay lastPossibleLessonDay = executionCourse.getMaxLessonsPeriod().getRight();
    for (final Interval interval : getAllLessonIntervals()) {
        final Integer week = Weeks.weeksBetween(firstPossibleLessonDay, interval.getStart().toLocalDate()).getWeeks() + 1;
        weeks.add(week);
    }

    final StringBuilder builder = new StringBuilder();
    final Integer[] weeksA = weeks.toArray(new Integer[0]);
    for (int i = 0; i < weeksA.length; i++) {
        if (i == 0) {
            builder.append(weeksA[i]);
        } else if (i == weeksA.length - 1 || (weeksA[i]) + 1 != (weeksA[i + 1])) {
            final String seperator = (weeksA[i - 1]) + 1 == (weeksA[i]) ? " - " : ", ";
            builder.append(seperator);
            builder.append(weeksA[i]);
        } else if ((weeksA[i - 1]) + 1 != weeksA[i]) {
            builder.append(", ");
            builder.append(weeksA[i]);
        }
    }
    return builder.toString();
}
 
Example #8
Source File: InfoLessonInstanceAggregation.java    From fenixedu-academic with GNU Lesser General Public License v3.0 5 votes vote down vote up
public SortedSet<Integer> getWeeks(final Interval lessonInterval) {
    final SortedSet<Integer> weeks = new TreeSet<Integer>();
    final LocalDate firstPossibleLessonDay = lessonInterval.getStart().toLocalDate();
    for (final LocalDate localDate : dates) {
        final Integer week = Weeks.weeksBetween(firstPossibleLessonDay, localDate).getWeeks() + 1;
        weeks.add(week);
    }
    return weeks;
}
 
Example #9
Source File: BaseNotificationContent.java    From incubator-pinot with Apache License 2.0 5 votes vote down vote up
/**
 * Convert comparison mode to Period
 */
protected static Period getBaselinePeriod(COMPARE_MODE compareMode) {
  switch (compareMode) {
    case Wo2W:
      return Weeks.TWO.toPeriod();
    case Wo3W:
      return Weeks.THREE.toPeriod();
    case Wo4W:
      return Weeks.weeks(4).toPeriod();
    case WoW:
    default:
      return Weeks.ONE.toPeriod();
  }
}
 
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: 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 #12
Source File: EmailHelper.java    From incubator-pinot with Apache License 2.0 5 votes vote down vote up
public static Period getBaselinePeriod(AlertConfigBean.COMPARE_MODE compareMode) {
  switch (compareMode) {
    case Wo2W:
      return Weeks.TWO.toPeriod();
    case Wo3W:
      return Weeks.THREE.toPeriod();
    case Wo4W:
      return Weeks.weeks(4).toPeriod();
    case WoW:
    default:
      return Weeks.ONE.toPeriod();
  }
}
 
Example #13
Source File: DateUtils.java    From weMessage with GNU Affero General Public License v3.0 4 votes vote down vote up
public static boolean isSameWeek(Date date){
    return Weeks.weeksBetween(new DateTime(date), new DateTime(Calendar.getInstance().getTime())).getWeeks() == 0;
}
 
Example #14
Source File: DateUtils.java    From joda-time-android with Apache License 2.0 4 votes vote down vote up
/**
 * Return string describing the time until/elapsed time since 'time' formatted like
 * "[relative time/date], [time]".
 *
 * See {@link android.text.format.DateUtils#getRelativeDateTimeString} for full docs.
 *
 * @param context the context
 * @param time some time
 * @param transitionResolution the elapsed time (period) at which
 * to stop reporting relative measurements. Periods greater
 * than this resolution will default to normal date formatting.
 * For example, will transition from "6 days ago" to "Dec 12"
 * when using Weeks.ONE.  If null, defaults to Days.ONE.
 * Clamps to min value of Days.ONE, max of Weeks.ONE.
 * @param flags flags for getRelativeTimeSpanString() (if duration is less than transitionResolution)
 */
public static CharSequence getRelativeDateTimeString(Context context, ReadableInstant time,
                                                     ReadablePeriod transitionResolution, int flags) {
    Resources r = context.getResources();

    // We set the millis to 0 so we aren't off by a fraction of a second when counting duration
    DateTime now = DateTime.now(time.getZone()).withMillisOfSecond(0);
    DateTime timeDt = new DateTime(time).withMillisOfSecond(0);
    boolean past = !now.isBefore(timeDt);
    Duration duration = past ? new Duration(timeDt, now) : new Duration(now, timeDt);

    // getRelativeTimeSpanString() doesn't correctly format relative dates
    // above a week or exact dates below a day, so clamp
    // transitionResolution as needed.
    Duration transitionDuration;
    Duration minDuration = Days.ONE.toPeriod().toDurationTo(timeDt);
    if (transitionResolution == null) {
        transitionDuration = minDuration;
    }
    else {
        transitionDuration = past ? transitionResolution.toPeriod().toDurationTo(now) :
            transitionResolution.toPeriod().toDurationFrom(now);
        Duration maxDuration = Weeks.ONE.toPeriod().toDurationTo(timeDt);
        if (transitionDuration.isLongerThan(maxDuration)) {
            transitionDuration = maxDuration;
        }
        else if (transitionDuration.isShorterThan(minDuration)) {
            transitionDuration = minDuration;
        }
    }

    CharSequence timeClause = formatDateRange(context, time, time, FORMAT_SHOW_TIME);

    String result;
    if (!duration.isLongerThan(transitionDuration)) {
        CharSequence relativeClause = getRelativeTimeSpanString(context, time, flags);
        result = r.getString(R.string.joda_time_android_relative_time, relativeClause, timeClause);
    }
    else {
        CharSequence dateClause = getRelativeTimeSpanString(context, time, false);
        result = r.getString(R.string.joda_time_android_date_time, dateClause, timeClause);
    }

    return result;
}
 
Example #15
Source File: TestAllClassDataTypesAreSupported.java    From jfixture with MIT License 4 votes vote down vote up
@Test
public void creates_instance_of_Weeks() {
    Weeks weeks = fixture.create(Weeks.class);
    assertThat(weeks, notNullValue());
    assertThat(weeks, is(Weeks.weeks(52)));
}
 
Example #16
Source File: SurveySettingsService.java    From JDeSurvey with GNU Affero General Public License v3.0 4 votes vote down vote up
@Transactional(readOnly = false)
@SuppressWarnings("unchecked")
public void sendEmailReminders() {
	try {
		int currentDayOfWeek = new DateTime().getDayOfWeek();
		int currentDayOfMonth = new DateTime().getDayOfMonth();
		DateTime todayDateTime = new DateTime();

		for (SurveyDefinition surveyDefinition : surveyDefinitionDAO.findAllInternal()){
			if (surveyDefinition.getSendAutoReminders()&& surveyDefinition.getUsers().size()>0 && surveyDefinition.getStatusAsString().equals("P")) {
				Date  lastSentDate = surveyDefinition.getAutoReminderLastSentDate(); 
				switch (surveyDefinition.getAutoRemindersFrequency()) {
				case  WEEKLY:
					int weeks;
					if (lastSentDate !=null) {weeks = Weeks.weeksBetween(new DateTime(lastSentDate),todayDateTime).getWeeks();
					}
					
					else {weeks = 1000;}
					if (weeks >= surveyDefinition.getAutoRemindersWeeklyOccurrence()) {
						for (Day day : surveyDefinition.getAutoRemindersDays()) {
							if (day.getId().equals(new Long(currentDayOfWeek))) {
								sendEmailReminder(surveyDefinition);
								
							}
						}
					}
					break;
				case MONTHLY:
					int months;
					if (lastSentDate !=null) {months = Months.monthsBetween(new DateTime(lastSentDate), todayDateTime).getMonths();
					}
					else {months = 1000;}
					if (months>=surveyDefinition.getAutoRemindersMonthlyOccurrence() && surveyDefinition.getAutoRemindersDayOfMonth().equals(currentDayOfMonth)) {
						sendEmailReminder(surveyDefinition);
						}
					break;
				}
			}
		}
	}
	catch (RuntimeException e) {
		log.error(e.getMessage(),e);
	} 
}
 
Example #17
Source File: RWeekCalendar.java    From RWeekCalendar with MIT License 4 votes vote down vote up
public int getWeekBetweenDates(DateTime start, DateTime end) {

        int diff = Weeks.weeksBetween(start, end).getWeeks();
        diff = diff + 1;
        return diff;
    }
 
Example #18
Source File: RWeekCalendar.java    From RWeekCalendar with MIT License 4 votes vote down vote up
/**
 * Set set date of the selected week
 *
 * @param calendar
 */
public void setDateWeek(Calendar calendar) {

    LocalDateTime ldt = LocalDateTime.fromCalendarFields(calendar);

    AppController.getInstance().setSelected(ldt);


    int nextPage = Weeks.weeksBetween(mStartDate, ldt).getWeeks();


    if (nextPage >= 0 && nextPage < getWeekBetweenDates(start, end)) {

        pager.setCurrentItem(nextPage);
        calenderListener.onSelectDate(ldt);
        WeekFragment fragment = (WeekFragment) pager.getAdapter().instantiateItem(pager, nextPage);
        fragment.ChangeSelector(ldt);
    }


}
 
Example #19
Source File: WeeksBetweenDates.java    From levelup-java-examples with Apache License 2.0 3 votes vote down vote up
@Test
public void weeks_between_two_dates_in_java_with_joda () {
	
	DateTime start = new DateTime(2005, 1, 1, 0, 0, 0, 0);
	DateTime end = new DateTime(2006, 1, 1, 0, 0, 0, 0);
	
	Weeks weeks = Weeks.weeksBetween(start, end);

	int weeksInYear = weeks.getWeeks();
	
	assertEquals(52, weeksInYear);
}