Java 类org.joda.time.Months 实例源码

项目:SOS-The-Healthcare-Companion    文件:DatabaseHandler.java   
public List<Integer> getAverageGlucoseReadingsByMonth() {
    JodaTimeAndroid.init(mContext);

    DateTime maxDateTime = new DateTime(realm.where(GlucoseReading.class).maximumDate("created").getTime());
    DateTime minDateTime = new DateTime(realm.where(GlucoseReading.class).minimumDate("created").getTime());

    DateTime currentDateTime = minDateTime;
    DateTime newDateTime = minDateTime;

    ArrayList<Integer> averageReadings = new ArrayList<Integer>();

    // The number of months is at least 1 since we do have average for the current week even if incomplete
    int monthsNumber = Months.monthsBetween(minDateTime, maxDateTime).getMonths() + 1;

    for (int i = 0; i < monthsNumber; i++) {
        newDateTime = currentDateTime.plusMonths(1);
        RealmResults<GlucoseReading> readings = realm.where(GlucoseReading.class)
                .between("created", currentDateTime.toDate(), newDateTime.toDate())
                .findAll();
        averageReadings.add(((int) readings.average("reading")));
        currentDateTime = newDateTime;
    }
    return averageReadings;
}
项目:SOS-The-Healthcare-Companion    文件:DatabaseHandler.java   
public List<String> getGlucoseDatetimesByMonth() {
    JodaTimeAndroid.init(mContext);

    DateTime maxDateTime = new DateTime(realm.where(GlucoseReading.class).maximumDate("created").getTime());
    DateTime minDateTime = new DateTime(realm.where(GlucoseReading.class).minimumDate("created").getTime());

    DateTime currentDateTime = minDateTime;
    DateTime newDateTime = minDateTime;

    ArrayList<String> finalMonths = new ArrayList<String>();

    // The number of months is at least 1 because current month is incomplete
    int monthsNumber = Months.monthsBetween(minDateTime, maxDateTime).getMonths() + 1;

    DateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    for (int i = 0; i < monthsNumber; i++) {
        newDateTime = currentDateTime.plusMonths(1);
        finalMonths.add(inputFormat.format(newDateTime.toDate()));
        currentDateTime = newDateTime;
    }
    return finalMonths;
}
项目:Artificial-Intelligent-chat-bot-    文件:IntervalUtils.java   
public static int getMonthsBetween(final String date1, final String date2, String format){
    try {
    final DateTimeFormatter fmt =
            DateTimeFormat
                    .forPattern(format)
                    .withChronology(
                            LenientChronology.getInstance(
                                    GregorianChronology.getInstance()));
    return Months.monthsBetween(
            fmt.parseDateTime(date1),
            fmt.parseDateTime(date2)
    ).getMonths();
    } catch (Exception ex) {
        ex.printStackTrace();
        return 0;
    }
}
项目:CustomizableCalendar    文件:Calendar.java   
public Calendar(DateTime firstMonth, DateTime lastMonth) {
    this.firstMonth = firstMonth;
    this.firstDayOfWeek = java.util.Calendar.getInstance(Locale.getDefault()).getFirstDayOfWeek();

    DateTime startMonth = firstMonth.plusMonths(1);
    int monthsBetweenCount = Months.monthsBetween(firstMonth, lastMonth).getMonths();

    months = new ArrayList<>();

    months.add(firstMonth);
    currentMonth = firstMonth;

    DateTime monthToAdd = new DateTime(startMonth.getYear(), startMonth.getMonthOfYear(), 1, 0, 0);
    for (int i = 0; i <= monthsBetweenCount; i++) {
        months.add(monthToAdd);
        monthToAdd = monthToAdd.plusMonths(1);
    }
}
项目:DSSApp    文件:DSSExport.java   
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());

}
项目:jasperreports    文件:DateTimeFunctions.java   
/**
 * Returns the number of months between two dates.
 */
@Function("MONTHS")
@FunctionParameters({
    @FunctionParameter("startDate"),
    @FunctionParameter("endDate")})
public Integer MONTHS(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 Months.monthsBetween(dt1, dt2).getMonths();
    }
}
项目:BudgetMaster    文件:RepeatingPaymentUpdater.java   
private ArrayList<DateTime> getCorrectRepeatingDates(RepeatingPayment payment, DateTime now)
{
    ArrayList<DateTime> dates = new ArrayList<>();
    DateTime startDate = DateTime.parse(payment.getDate());

    //repeat every x days
    if(payment.getRepeatInterval() != 0)
    {           
        int numberOfDays = Days.daysBetween(startDate, now).getDays();          
        int occurrences = numberOfDays / payment.getRepeatInterval();
        for(int i = 0; i <= occurrences; i++)
        {
            dates.add(startDate.plusDays(i * payment.getRepeatInterval()));
        }
    }
    //repeat every month on day x
    else
    {
        int numberOfMonths = Months.monthsBetween(startDate.withDayOfMonth(payment.getRepeatMonthDay()), now).getMonths();
        for(int i = 0; i <= numberOfMonths; i++)
        {
            dates.add(startDate.plusMonths(i));
        }               
    }
    return dates;
}
项目:Daytripper    文件:IntervalUtils.java   
public static int getMonthsBetween(final String date1, final String date2, String format){
    try {
    final DateTimeFormatter fmt =
            DateTimeFormat
                    .forPattern(format)
                    .withChronology(
                            LenientChronology.getInstance(
                                    GregorianChronology.getInstance()));
    return Months.monthsBetween(
            fmt.parseDateTime(date1),
            fmt.parseDateTime(date2)
    ).getMonths();
    } catch (Exception ex) {
        ex.printStackTrace();
        return 0;
    }
}
项目:program-ab    文件:IntervalUtils.java   
public static int getMonthsBetween(final String date1, final String date2, String format){
    try {
    final DateTimeFormatter fmt =
            DateTimeFormat
                    .forPattern(format)
                    .withChronology(
                            LenientChronology.getInstance(
                                    GregorianChronology.getInstance()));
    return Months.monthsBetween(
            fmt.parseDateTime(date1),
            fmt.parseDateTime(date2)
    ).getMonths();
    } catch (Exception ex) {
        ex.printStackTrace();
        return 0;
    }
}
项目:jfixture    文件:BaseSingleFieldPeriodRelay.java   
@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();
}
项目:spork-streaming    文件:MonthsBetween.java   
@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
    Months m = Months.monthsBetween(endDate, startDate);
    // joda limitation, only integer range, at the risk of overflow, need to be improved
    return (long) m.getMonths();

}
项目:spork-streaming    文件:ISOMonthsBetween.java   
@Override
public Long exec(Tuple input) throws IOException
{
    if (input == null || input.size() < 2) {
        return null;
    }

    // Set the time to default or the output is in UTC
    DateTimeZone.setDefault(DateTimeZone.UTC);

    DateTime startDate = new DateTime(input.get(0).toString());
    DateTime endDate = new DateTime(input.get(1).toString());

    // Larger value first
    Months m = Months.monthsBetween(endDate, startDate);
    long months = m.getMonths();

    return months;

}
项目:riscoss-platform    文件:GitRiskDataCollector.java   
/**
 * Obtain the indicators from the statistics and stores them into the im
 * 
 * @param im indicatorMap to store the indicators
 * @param statistics statistics of the git.
 */
private void storeAllMeasures(IndicatorsMap im, GitLogStatistics statistics)
{
    DateTime dt = new DateTime(statistics.firstCommitDate);
    Months months = Months.monthsBetween(dt, new DateTime());
    Weeks weeks = Weeks.weeksBetween(dt, new DateTime());

    im.add("git average-commits-per-month", (double) statistics.totalCommits / months.getMonths());
    im.add("git average-commits-per-week", (double) statistics.totalCommits / weeks.getWeeks());
    im.add("git average-commits-per-committer", (double) statistics.totalCommits / statistics.totalCommitters);
    im.add("git average-files-changed-per-committer", (double) statistics.totalFilesChanged
        / statistics.totalCommitters);
    im.add("git average-lines-added-per-commmit", (double) statistics.totalLinesAdded / statistics.totalCommits);
    im.add("git average-lines-removed-per-commit", (double) statistics.totalLinesRemoved / statistics.totalCommits);
    im.add("git average-files-changed-per-commit", (double) statistics.totalFilesChanged / statistics.totalCommits);

    im.add("git distribution-commits-by-hour", RiskDataType.DISTRIBUTION,
        getDistribution(statistics.commitsByHour, statistics.totalCommits));

    im.add("git distribution-commits-by-weekday", RiskDataType.DISTRIBUTION,
        getDistribution(statistics.commitsByWeekday, statistics.totalCommits));

}
项目:spork    文件:MonthsBetween.java   
@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
    Months m = Months.monthsBetween(endDate, startDate);
    // joda limitation, only integer range, at the risk of overflow, need to be improved
    return (long) m.getMonths();

}
项目:spork    文件:ISOMonthsBetween.java   
@Override
public Long exec(Tuple input) throws IOException
{
    if (input == null || input.size() < 2) {
        return null;
    }

    if (input.get(0) == null || input.get(1) == null) {
        return null;
    }

    DateTime startDate = new DateTime(input.get(0).toString());
    DateTime endDate = new DateTime(input.get(1).toString());

    // Larger value first
    Months m = Months.monthsBetween(endDate, startDate);
    long months = m.getMonths();

    return months;

}
项目:GMM    文件:BackupAccessService.java   
@Autowired
public BackupAccessService(DataConfigService config, BackupFileService service) {
    this.config = config;
    this.fileService = service;

    // timed backups
    monthlyBackup = new ConditionalBackupExecutor("monthly", 6, (now, last) -> {
            final Months duration = Months.monthsBetween(last, now);
            return duration.getMonths() >= 1;
        }
    );
    daylyBackup = new ConditionalBackupExecutor("dayly", 7, (now, last) -> {
            final Days duration = Days.daysBetween(last, now);
            return duration.getDays() >= 1;
        }
    );
    hourlyBackup = new ConditionalBackupExecutor("hourly", 24, (now, last) -> {
            final Hours duration = Hours.hoursBetween(last, now);
            return duration.getHours() >= 1;
        }
    );
    // triggered backups
    triggeredBackup = new BackupExecutor("triggered", 100);
}
项目:fenixedu-academic    文件:Person.java   
public boolean areContactsRecent(final Class<? extends PartyContact> contactClass, final int daysNotUpdated) {
    final List<? extends PartyContact> partyContacts = getPartyContacts(contactClass);
    boolean isUpdated = false;
    for (final PartyContact partyContact : partyContacts) {
        if (partyContact.getLastModifiedDate() == null) {
            isUpdated = isUpdated || false;
        } else {
            final DateTime lastModifiedDate = partyContact.getLastModifiedDate();
            final DateTime now = new DateTime();
            final Months months = Months.monthsBetween(lastModifiedDate, now);
            if (months.getMonths() > daysNotUpdated) {
                isUpdated = isUpdated || false;
            } else {
                isUpdated = isUpdated || true;
            }
        }
    }
    return isUpdated;
}
项目:estatio    文件:InvoiceAttributesVM.java   
private String getFrequencyElseNull() {
    final SortedSet<InvoiceItem> items = invoice.getItems();
    if(items.isEmpty()) {
        return null;
    }
    final InvoiceItem item = items.first();
    final LocalDate startDate = item.getStartDate();
    final LocalDate endDate = item.getEndDate();
    if(startDate == null || endDate == null) {
        return null;
    }
    Months months = Months.monthsBetween(startDate, endDate.plusDays(1));
    switch (months.getMonths()) {
    case 12:
        return "YEAR";
    case 3:
        return "QUARTER";
    case 1:
        return "MONTH";
    }
    return null;
}
项目:datefy    文件:Datefy.java   
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();
        }
    }
}
项目:sedge    文件:ISOMonthsBetween.java   
@Override
public Long exec(Tuple input) throws IOException
{
    if (input == null || input.size() < 2) {
        return null;
    }

    // Set the time to default or the output is in UTC
    DateTimeZone.setDefault(DateTimeZone.UTC);

    DateTime startDate = new DateTime(input.get(0).toString());
    DateTime endDate = new DateTime(input.get(1).toString());

    // Larger value first
    Months m = Months.monthsBetween(endDate, startDate);
    long months = m.getMonths();

    return months;

}
项目:citizen-sdk-android    文件:TokenService.java   
@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;
}
项目:PocketKnell    文件:KnellActivity.java   
@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()));
}
项目:micro-ecommerce    文件:CreditCard.java   
public CreditCard(CreditCardNumber number, String cardHolderName, Months expiryMonth, Years expiryYear) {
    super();
    this.number = number;
    this.cardHolderName = cardHolderName;
    this.expiryMonth = expiryMonth;
    this.expiryYear = expiryYear;
}
项目:azkaban    文件:Schedule.java   
public static ReadablePeriod parsePeriodString(String periodStr) {
  ReadablePeriod period;
  char periodUnit = periodStr.charAt(periodStr.length() - 1);
  if (periodUnit == 'n') {
    return null;
  }

  int periodInt =
      Integer.parseInt(periodStr.substring(0, periodStr.length() - 1));
  switch (periodUnit) {
  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;
}
项目:azkaban    文件:Utils.java   
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;
}
项目:azkaban    文件:Schedule.java   
public static ReadablePeriod parsePeriodString(String periodStr) {
  ReadablePeriod period;
  char periodUnit = periodStr.charAt(periodStr.length() - 1);
  if (periodUnit == 'n') {
    return null;
  }

  int periodInt =
      Integer.parseInt(periodStr.substring(0, periodStr.length() - 1));
  switch (periodUnit) {
  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;
}
项目:beam    文件:CalendarWindows.java   
@Override
public IntervalWindow assignWindow(Instant timestamp) {
  DateTime datetime = new DateTime(timestamp, timeZone);

  int monthOffset =
      Months.monthsBetween(startDate.withDayOfMonth(dayOfMonth), datetime).getMonths()
      / number * number;

  DateTime begin = startDate.withDayOfMonth(dayOfMonth).plusMonths(monthOffset);
  DateTime end = begin.plusMonths(number);

  return new IntervalWindow(begin.toInstant(), end.toInstant());
}
项目: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;
}
项目: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;
}
项目:NaturalDateFormat    文件:RelativeDateFormat.java   
private void formatMonths(DateTime now, DateTime then, StringBuffer text) {
    int monthsBetween = Months.monthsBetween(now.toLocalDate(), then.toLocalDate()).getMonths();
    if (monthsBetween == 0) {
        if ((format & DAYS) != 0) {
            formatDays(now, then, text);
        } else {
            text.append(context.getString(R.string.thisMonth));
        }
    } else if (monthsBetween > 0) {    // in N months
        text.append(context.getResources().getQuantityString(R.plurals.carbon_inMonths, monthsBetween, monthsBetween));
    } else {    // N months ago
        text.append(context.getResources().getQuantityString(R.plurals.carbon_monthsAgo, -monthsBetween, -monthsBetween));
    }
}
项目:gcplot    文件:CassandraGCEventRepository.java   
/**
 * Returns a range of dates in format YYYY-MM, starting from the most recent one.
 *
 * @param range
 * @return
 */
protected List<String> dates(Range range) {
    return Lists.reverse(IntStream.range(0, Months.monthsBetween(
            range.from().monthOfYear().roundFloorCopy(),
            range.to().monthOfYear().roundCeilingCopy()).getMonths())
            .mapToObj(i -> range.from().plusMonths(i).toString(DATE_PATTERN))
            .collect(Collectors.toList()));
}
项目:CodePath-TodoApp    文件:TimeUtils.java   
private static String toMonths(DateTime date, DateTime now) {
    int result = Months.monthsBetween(date, now).getMonths();
    if (Math.abs(result) >= 1) {
        return Math.abs(result) == 1 ? (result == 1 ? "Last" : "Next") + " month" :
                toReference(Math.abs(result), result, " months ");
    }
    return null;
}
项目:effektif    文件:AfterRelativeTime.java   
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;
}
项目:azkaban-customization    文件:Schedule.java   
public static ReadablePeriod parsePeriodString(String periodStr) {
    ReadablePeriod period;
    char periodUnit = periodStr.charAt(periodStr.length() - 1);
    if (periodUnit == 'n') {
        return null;
    }

    int periodInt = Integer.parseInt(periodStr.substring(0,
            periodStr.length() - 1));
    switch (periodUnit) {
    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;
}
项目:azkaban-customization    文件:Utils.java   
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;
}
项目:azkaban-customization    文件:Schedule.java   
public static ReadablePeriod parsePeriodString(String periodStr) {
    ReadablePeriod period;
    char periodUnit = periodStr.charAt(periodStr.length() - 1);
    if (periodUnit == 'n') {
        return null;
    }

    int periodInt = Integer.parseInt(periodStr.substring(0,
            periodStr.length() - 1));
    switch (periodUnit) {
    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;
}
项目: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);
}
项目:effektif    文件:AfterRelativeTime.java   
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;
}
项目:SimpleStrengthLog    文件:Util.java   
public static String getRelativeDate(LocalDate today, LocalDate previousDate) {
    //These calculations are relatively expensive, so we'll only do the ones we absolutely need to
    int years = Years.yearsBetween(previousDate, today).getYears();
    if (years > 1) {
        return years + " Years Ago";
    } else if (years == 1) {
        return "One Year Ago";
    } else {
        int months = Months.monthsBetween(previousDate, today).getMonths();
        if (months > 1) {
            return months + " Months Ago";
        } else if (months == 1) {
            return "1 Month Ago";
        } else {
            int weeks = Weeks.weeksBetween(previousDate, today).getWeeks();
            if (weeks > 1) {
                return weeks + " Weeks Ago";
            } else if (weeks == 1) {
                return "1 Week Ago";
            } else {
                int days = Days.daysBetween(previousDate, today).getDays();
                if (days > 1) {
                    return days + " Days Ago";
                } else if (days == 1) {
                    return "Yesterday";
                } else {
                    return "Previously";
                }
            }
        }
    }
}
项目:divconq    文件:TimeUtil.java   
/**
 * return number of months since Jan 1, 1970
 * 
 * @param v date to calculate month number off of
 * @return number of months
 */
static public int getMonthNumber(DateTime v) {
    DateTime root = new DateTime(1970, 1, 1, 0, 0, 0, 0, v.getZone());   // use the same zone

    return Months.monthsBetween(root, v).getMonths();

    //int n = (v.getYear() - 1970) * 12;  
    //return n + v.getMonthOfYear() - 1;
}