org.joda.time.Weeks源码实例Demo

类org.joda.time.Weeks源码实例Demo

下面列出了org.joda.time.Weeks 类实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: stategen   文件: DatetimeUtil.java
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;
    }
}
 
源代码2 项目: jasperreports   文件: DateTimeFunctions.java
/**
 * 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();
	}
}
 
源代码3 项目: jfixture   文件: BaseSingleFieldPeriodRelay.java
@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();
}
 
源代码4 项目: NCalendar   文件: CalendarUtil.java
/**
 * 获得两个日期距离几周
 *
 * @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();

}
 
源代码5 项目: data-polygamy   文件: FrameworkUtils.java
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;
}
 
源代码6 项目: data-polygamy   文件: FrameworkUtils.java
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;
}
 
源代码7 项目: CloverETL-Engine   文件: DateLib.java
@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;
}
 
源代码8 项目: sana.mobile   文件: Functions.java
/**
 * 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);
}
 
源代码9 项目: incubator-pinot   文件: EmailHelper.java
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();
  }
}
 
源代码10 项目: incubator-pinot   文件: BaseNotificationContent.java
/**
 * 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();
  }
}
 
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;
}
 
源代码12 项目: fenixedu-academic   文件: Lesson.java
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();
}
 
源代码13 项目: weMessage   文件: DateUtils.java
public static boolean isSameWeek(Date date){
    return Weeks.weeksBetween(new DateTime(date), new DateTime(Calendar.getInstance().getTime())).getWeeks() == 0;
}
 
源代码14 项目: RWeekCalendar   文件: RWeekCalendar.java
/**
 * 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);
    }


}
 
源代码15 项目: RWeekCalendar   文件: RWeekCalendar.java
public int getWeekBetweenDates(DateTime start, DateTime end) {

        int diff = Weeks.weeksBetween(start, end).getWeeks();
        diff = diff + 1;
        return diff;
    }
 
源代码16 项目: JDeSurvey   文件: SurveySettingsService.java
@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);
	} 
}
 
@Test
public void creates_instance_of_Weeks() {
    Weeks weeks = fixture.create(Weeks.class);
    assertThat(weeks, notNullValue());
    assertThat(weeks, is(Weeks.weeks(52)));
}
 
源代码18 项目: joda-time-android   文件: DateUtils.java
/**
 * 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;
}
 
源代码19 项目: levelup-java-examples   文件: WeeksBetweenDates.java
@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);
}
 
源代码评论
动弹
沙发等你来抢
 类所在包
 类方法
 同包方法