Example usage for org.joda.time DateTime plusMonths

List of usage examples for org.joda.time DateTime plusMonths

Introduction

In this page you can find the example usage for org.joda.time DateTime plusMonths.

Prototype

public DateTime plusMonths(int months) 

Source Link

Document

Returns a copy of this datetime plus the specified number of months.

Usage

From source file:org.fenixedu.spaces.domain.occupation.config.MonthlyConfig.java

License:Open Source License

private List<Interval> getDayOfMonthIntervals() {
    final List<Interval> intervals = new ArrayList<>();
    DateTime startDate = getInterval().getStart();
    DateTime endDate = getInterval().getEnd();
    DateTime start = startDate;
    while (start.isBefore(endDate) || start.isEqual(endDate)) {
        intervals.add(new Interval(start.withFields(getStartTime()), start.withFields(getEndTime())));
        start = start.plusMonths(getRepeatsEvery());
    }/*from   ww w.  ja v  a2 s . co  m*/
    return intervals;
}

From source file:org.fenixedu.spaces.ui.services.OccupationService.java

License:Open Source License

public List<Occupation> getOccupations(Integer month, Integer year, User user, String spaceName) {
    String spaceNameForSearch = spaceName == null ? null : spaceName.toLowerCase();
    DateTime start = new DateTime(year, month, 1, 0, 0);
    Interval interval = new Interval(start, start.plusMonths(1));
    Predicate<Occupation> userAndSpaceNamePredicate = o -> o.getSpaces().stream()
            .filter(s -> s.isOccupationMember(user)).filter(s -> matches(s, spaceNameForSearch)).findAny()
            .isPresent();/*from   w w  w.j  a  va 2 s .  co m*/
    return Bennu.getInstance().getOccupationSet().stream().filter(o -> o.getClass().equals(Occupation.class))
            .filter(userAndSpaceNamePredicate).filter(o -> o.overlaps(interval))
            .sorted((o1, o2) -> o2.getStart().compareTo(o1.getStart())).collect(Collectors.toList());
}

From source file:org.filteredpush.qc.date.DateUtils.java

License:Apache License

/**
 * Given a string that may be a date or a date range, extract a interval of
 * dates from that date range, up to the end milisecond of the last day.
 * /*from   ww  w  .  j a v a2  s .  c  om*/
 * @see DateUtils#extractDateInterval(String) which returns a pair of DateMidnights.
 * 
 * @param eventDate a string containing a dwc:eventDate from which to extract an interval.
 * @return an interval from the beginning of event date to the end of event date.
 */
public static Interval extractInterval(String eventDate) {
    Interval result = null;
    DateTimeParser[] parsers = { DateTimeFormat.forPattern("yyyy-MM").getParser(),
            DateTimeFormat.forPattern("yyyy").getParser(),
            ISODateTimeFormat.dateOptionalTimeParser().getParser() };
    DateTimeFormatter formatter = new DateTimeFormatterBuilder().append(null, parsers).toFormatter();
    if (eventDate != null && eventDate.contains("/") && isRange(eventDate)) {
        String[] dateBits = eventDate.split("/");
        try {
            // must be at least a 4 digit year.
            if (dateBits[0].length() > 3 && dateBits[1].length() > 3) {
                DateMidnight startDate = DateMidnight.parse(dateBits[0], formatter);
                DateTime endDate = DateTime.parse(dateBits[1], formatter);
                logger.debug(startDate);
                logger.debug(endDate);
                if (dateBits[1].length() == 4) {
                    result = new Interval(startDate, endDate.plusMonths(12).minus(1l));
                } else if (dateBits[1].length() == 7) {
                    result = new Interval(startDate, endDate.plusMonths(1).minus(1l));
                } else {
                    result = new Interval(startDate, endDate.plusDays(1).minus(1l));
                }
                logger.debug(result);
            }
        } catch (Exception e) {
            // not a date range
            logger.error(e.getMessage());
        }
    } else {
        try {
            DateMidnight startDate = DateMidnight.parse(eventDate, formatter);
            logger.debug(startDate);
            if (eventDate.length() == 4) {
                DateTime endDate = startDate.toDateTime().plusMonths(12).minus(1l);
                result = new Interval(startDate, endDate);
                logger.debug(result);
            } else if (eventDate.length() == 7) {
                DateTime endDate = startDate.toDateTime().plusMonths(1).minus(1l);
                result = new Interval(startDate, endDate);
                logger.debug(result);
            } else {
                DateTime endDate = startDate.toDateTime().plusDays(1).minus(1l);
                result = new Interval(startDate, endDate);
                logger.debug(result);
            }
        } catch (Exception e) {
            // not a date
            logger.error(e.getMessage());
        }
    }
    return result;
}

From source file:org.gephi.desktop.timeline.MinimalDrawer.java

License:Open Source License

private void paintUpperRulerForInterval(Graphics2D g2d, DateTime dtFrom, DateTime dtTo) {

    g2d.setFont(settings.graduations.font);
    g2d.setColor(settings.graduations.fontColor);
    int leftMargin = settings.graduations.leftMargin;
    int textTopPosition = settings.graduations.textTopPosition;
    int width = getWidth();
    int height = getHeight();
    // TODO take these from the model

    Interval interval = new Interval(dtFrom, dtTo);

    Period p = interval.toPeriod(PeriodType.days());
    // try to determine length if we had to show milliseconds

    int n = p.getDays();
    int unitSize = (int) (settings.graduations.fontMetrics.getStringBounds("wednesday  ", null)).getWidth();
    if (n < (width / unitSize)) {
        //System.out.println("jour");
        for (int i = 0; i < n; i++) {
            g2d.drawString(dtFrom.plusDays(i).dayOfWeek().getAsText(LOCALE), leftMargin + 2 + i * (width / n),
                    textTopPosition);/*from   w  w  w  . j av a2 s. c om*/
            g2d.drawLine(leftMargin + i * (width / n), 2, leftMargin + i * (width / n),
                    height - settings.graduations.textBottomMargin);
            paintSmallGraduations(g2d, leftMargin + i * (width / n), leftMargin + (i + 1) * (width / n),
                    Hours.hoursBetween(dtFrom.plusDays(i), dtFrom.plusDays(i + 1)).getHours());
        }
        return;
    }

    unitSize = (int) (settings.graduations.fontMetrics.getStringBounds("wed ", null)).getWidth();
    if (n < (width / unitSize)) {
        //System.out.println("jou");
        for (int i = 0; i < n; i++) {
            g2d.drawString(dtFrom.plusDays(i).dayOfWeek().getAsShortText(LOCALE),
                    leftMargin + 2 + i * (width / n), textTopPosition);
            g2d.drawLine(leftMargin + i * (width / n), 2, leftMargin + i * (width / n),
                    height - settings.graduations.textBottomMargin);

            paintSmallGraduations(g2d, leftMargin + i * (width / n), leftMargin + (i + 1) * (width / n),
                    Hours.hoursBetween(dtFrom.plusDays(i), dtFrom.plusDays(i + 1)).getHours());
        }
        return;
    }

    p = interval.toPeriod(PeriodType.days());
    n = p.getDays();
    unitSize = (int) (settings.graduations.fontMetrics.getStringBounds("30", null)).getWidth();
    if (n < (width / unitSize)) {
        //System.out.println("j");
        for (int i = 0; i < n; i++) {
            g2d.drawString("" + (dtFrom.getDayOfMonth() + i), leftMargin + 2 + i * (width / n),
                    textTopPosition);
            g2d.drawLine(leftMargin + i * (width / n), 2, leftMargin + i * (width / n),
                    height - settings.graduations.textBottomMargin);

            paintSmallGraduations(g2d, leftMargin + i * (width / n), leftMargin + (i + 1) * (width / n),
                    Hours.hoursBetween(dtFrom.plusDays(i), dtFrom.plusDays(i + 1)).getHours());
        }
        return;
    }

    p = interval.toPeriod(PeriodType.months());
    n = p.getMonths();
    unitSize = (int) (settings.graduations.fontMetrics.getStringBounds("September  ", null)).getWidth();
    if (n < (width / unitSize)) {
        //System.out.println("mois");
        for (int i = 0; i < n; i++) {
            g2d.drawString(dtFrom.plusMonths(i).monthOfYear().getAsText(LOCALE),
                    leftMargin + 2 + i * (width / n), textTopPosition);
            g2d.drawLine(leftMargin + i * (width / n), 2, leftMargin + i * (width / n),
                    height - settings.graduations.textBottomMargin);

            paintSmallGraduations(g2d, leftMargin + i * (width / n), leftMargin + (i + 1) * (width / n),
                    Days.daysBetween(dtFrom.plusMonths(i), dtFrom.plusMonths(i + 1)).getDays());
        }
        return;
    }

    unitSize = (int) (settings.graduations.fontMetrics.getStringBounds("dec ", null)).getWidth();
    if (n < (width / unitSize)) {
        //System.out.println("mo");
        for (int i = 0; i < n; i++) {
            g2d.drawString(dtFrom.plusMonths(i).monthOfYear().getAsShortText(LOCALE),
                    leftMargin + 2 + i * (width / n), textTopPosition);
            g2d.drawLine(leftMargin + i * (width / n), 2, leftMargin + i * (width / n),
                    height - settings.graduations.textBottomMargin);
            paintSmallGraduations(g2d, leftMargin + i * (width / n), leftMargin + (i + 1) * (width / n),
                    Days.daysBetween(dtFrom.plusMonths(i), dtFrom.plusMonths(i + 1)).getDays());
        }
        return;
    }

    unitSize = (int) (settings.graduations.fontMetrics.getStringBounds("29 ", null)).getWidth();
    if (n < (width / unitSize)) {
        //System.out.println("m");
        for (int i = 0; i < n; i++) {
            g2d.drawString("" + (dtFrom.getMonthOfYear() + i), leftMargin + 2 + i * (width / n),
                    textTopPosition);
            g2d.drawLine(leftMargin + i * (width / n), 2, leftMargin + i * (width / n),
                    height - settings.graduations.textBottomMargin);
            paintSmallGraduations(g2d, leftMargin + i * (width / n), leftMargin + (i + 1) * (width / n),
                    Days.daysBetween(dtFrom.plusMonths(i), dtFrom.plusMonths(i + 1)).getDays());
        }
        return;
    }

    p = interval.toPeriod(PeriodType.years());
    n = p.getYears();
    unitSize = (int) (settings.graduations.fontMetrics.getStringBounds("1980 ", null)).getWidth();
    if (n < (width / unitSize)) {
        //System.out.println("year");
        for (int i = 0; i < n; i++) {
            g2d.drawString("" + (dtFrom.getYear() + i), leftMargin + 2 + i * (width / n), textTopPosition);
            g2d.drawLine(leftMargin + i * (width / n), 2, leftMargin + i * (width / n),
                    height - settings.graduations.textBottomMargin);
            paintSmallGraduations(g2d, leftMargin + i * (width / n), leftMargin + (i + 1) * (width / n),
                    Months.monthsBetween(dtFrom.plusYears(i), dtFrom.plusYears(i + 1)).getMonths());
        }
        return;
    }

    int group = 10;
    n = p.getYears() / group;
    if (n < (width / unitSize)) {
        //System.out.println("10 years");
        for (int i = 0; i < n; i++) {
            g2d.drawString("" + (dtFrom.getYear() + i * group), leftMargin + 2 + i * (width / n),
                    textTopPosition);
            g2d.drawLine(leftMargin + i * (width / n), 2, leftMargin + i * (width / n),
                    height - settings.graduations.textBottomMargin);
            paintSmallGraduations(g2d, leftMargin + i * (width / n), leftMargin + (i + 1) * (width / n), Months
                    .monthsBetween(dtFrom.plusYears(i * group), dtFrom.plusYears((i + 1) * group)).getMonths());
        }
        return;
    }
    group = 20;
    n = p.getYears() / group;
    if (n < (width / unitSize)) {
        //System.out.println("20 years");
        for (int i = 0; i < n; i++) {
            g2d.drawString("" + (dtFrom.getYear() + i * group), leftMargin + 2 + i * (width / n),
                    textTopPosition);
            g2d.drawLine(leftMargin + i * (width / n), 2, leftMargin + i * (width / n),
                    height - settings.graduations.textBottomMargin);
            paintSmallGraduations(g2d, leftMargin + i * (width / n), leftMargin + (i + 1) * (width / n), Months
                    .monthsBetween(dtFrom.plusYears(i * group), dtFrom.plusYears((i + 1) * group)).getMonths());
        }
        return;
    }
    group = 50;
    n = p.getYears() / group;
    if (n < (width / unitSize)) {
        //System.out.println("50 years");
        for (int i = 0; i < n; i++) {
            g2d.drawString("" + (dtFrom.getYear() + i * group), leftMargin + 2 + i * (width / n),
                    textTopPosition);
            g2d.drawLine(leftMargin + i * (width / n), 2, leftMargin + i * (width / n),
                    height - settings.graduations.textBottomMargin);
            paintSmallGraduations(g2d, leftMargin + i * (width / n), leftMargin + (i + 1) * (width / n), Months
                    .monthsBetween(dtFrom.plusYears(i * group), dtFrom.plusYears((i + 1) * group)).getMonths());
        }
        return;
    }
    group = 100;
    n = p.getYears() / group;
    if (n / 100 < (width / unitSize)) {
        //System.out.println("100 years");
        for (int i = 0; i < n; i++) {
            g2d.drawString("" + (dtFrom.getYear() + i * group), leftMargin + 2 + i * (width / n),
                    textTopPosition);
            g2d.drawLine(leftMargin + i * (width / n), 2, leftMargin + i * (width / n),
                    height - settings.graduations.textBottomMargin);
            paintSmallGraduations(g2d, leftMargin + i * (width / n), leftMargin + (i + 1) * (width / n), Months
                    .monthsBetween(dtFrom.plusYears(i * group), dtFrom.plusYears((i + 1) * group)).getMonths());
        }
    }
    return;
}

From source file:org.itechkenya.leavemanager.domain.Contract.java

License:Open Source License

public List<PreviouslyCompletedPeriod> calculatePreviouslyCompletedPeriod() {

    List<PreviouslyCompletedPeriod> previousCompletedPeriods = new ArrayList<>();

    DateTime today = new DateTime(new Date());
    DateTime contractStartDate = new DateTime(this.getStartDate());

    SimpleDateFormat monthSdf = new SimpleDateFormat("yyyyMM");
    SimpleDateFormat yearSdf = new SimpleDateFormat("yyyy");

    DateTime earnDateTime;
    DateTime recordDateTime;//from ww  w.j  ava 2s .c om
    Date date;

    if (today.getDayOfMonth() >= contractStartDate.getDayOfMonth()) {
        earnDateTime = today.minusMonths(1);
    } else {
        earnDateTime = today.minusMonths(2);
    }
    recordDateTime = earnDateTime.plusMonths(1);
    date = DateTimeUtil.createDate(recordDateTime.getYear(), recordDateTime.getMonthOfYear(),
            contractStartDate.getDayOfMonth());
    previousCompletedPeriods
            .add(new PreviouslyCompletedPeriod(monthSdf.format(earnDateTime.toDate()), date, PeriodType.MONTH));

    int contractYearCount = this.calculateContractYear();
    if (contractYearCount > 1) {
        int previousContractYear = this.calculatePreviousContractYear(contractYearCount);

        Date recordDate = DateTimeUtil.createDate(previousContractYear + 1, contractStartDate.getMonthOfYear(),
                contractStartDate.getDayOfMonth());

        previousCompletedPeriods.add(new PreviouslyCompletedPeriod(String.valueOf(previousContractYear),
                recordDate, PeriodType.YEAR));
    }
    return previousCompletedPeriods;
}

From source file:org.jimcat.gui.histogram.image.DateTakenDimension.java

License:Open Source License

/**
 * this methode will reload statistical information from the library
 * //w w w  .j  a v a  2s . co m
 * @param library
 */
private void reloadValues(ImageLibrary library) {
    // get images
    List<Image> images = new ArrayList<Image>(library.getAll());

    // 1) find min / max date
    int i = 0;
    DateTime min = null;
    DateTime max = null;
    while (min == null && i < images.size()) {
        min = getDateTaken(images.get(i));
        max = min;
        i++;
    }

    if (min == null || max == null) {
        // result is an empty vector
        values = new int[RESOLUTION_COUNT][0];
        maxValues = new int[RESOLUTION_COUNT];
        minDate = null;
        fireStructureChangedEvent();
        return;
    }

    // iterate through images
    for (; i < images.size(); i++) {
        Image img = images.get(i);
        DateTime date = getDateTaken(img);
        if (date != null && min.isAfter(date)) {
            min = date;
        }
        if (date != null && max.isBefore(date)) {
            max = date;
        }
    }

    // save min dates
    // get references
    // must be a pure day
    DateTime dayRef = new DateTime(2000, 1, 1, 0, 0, 0, 0);

    // must be a monday
    DateTime weekRef = new DateTime(2000, 1, 3, 0, 0, 0, 0);

    // must be the first of any month
    DateTime monthRef = dayRef;

    minDate = new DateTime[RESOLUTION_COUNT];
    minDate[DAYS] = dayRef.plusDays(Days.daysBetween(dayRef, min).getDays());
    minDate[WEEKS] = weekRef.plusWeeks(Weeks.weeksBetween(weekRef, min).getWeeks());
    minDate[MONTHS] = monthRef.plusMonths(Months.monthsBetween(monthRef, min).getMonths());

    // 2) build arrays
    values = new int[RESOLUTION_COUNT][];
    values[DAYS] = new int[Days.daysBetween(minDate[DAYS], max).getDays() + 1];
    values[WEEKS] = new int[Weeks.weeksBetween(minDate[WEEKS], max).getWeeks() + 1];
    values[MONTHS] = new int[Months.monthsBetween(minDate[MONTHS], max).getMonths() + 1];

    // 3) fill in values
    for (Image img : images) {
        // extract date
        DateTime date = getDateTaken(img);
        if (date != null) {
            values[DAYS][Days.daysBetween(minDate[DAYS], date).getDays()]++;
            values[WEEKS][Weeks.weeksBetween(minDate[WEEKS], date).getWeeks()]++;
            values[MONTHS][Months.monthsBetween(minDate[MONTHS], date).getMonths()]++;
        }
    }

    // 4) get max values
    maxValues = new int[RESOLUTION_COUNT];
    for (int j = 0; j < RESOLUTION_COUNT; j++) {
        maxValues[j] = values[j][0];
        for (int k = 1; k < values[j].length; k++) {
            if (maxValues[j] < values[j][k]) {
                maxValues[j] = values[j][k];
            }
        }
    }

    // 6) notify listners
    fireStructureChangedEvent();
}

From source file:org.jruby.CompatVersion.java

License:LGPL

private static RubyTime createTime(IRubyObject recv, IRubyObject[] args, boolean gmt) {
        Ruby runtime = recv.getRuntime();
        int len = ARG_SIZE;

        if (args.length == 10) {
            args = new IRubyObject[] { args[5], args[4], args[3], args[2], args[1], args[0], runtime.getNil() };
        } else {//w  w w . ja  v  a 2 s.c  o m
            // MRI accepts additional wday argument which appears to be ignored.
            len = args.length;

            if (len < ARG_SIZE) {
                IRubyObject[] newArgs = new IRubyObject[ARG_SIZE];
                System.arraycopy(args, 0, newArgs, 0, args.length);
                for (int i = len; i < ARG_SIZE; i++) {
                    newArgs[i] = runtime.getNil();
                }
                args = newArgs;
                len = ARG_SIZE;
            }
        }

        if (args[0] instanceof RubyString) {
            args[0] = RubyNumeric.str2inum(runtime, (RubyString) args[0], 10, false);
        }

        int year = (int) RubyNumeric.num2long(args[0]);
        int month = 1;

        if (len > 1) {
            if (!args[1].isNil()) {
                IRubyObject tmp = args[1].checkStringType();
                if (!tmp.isNil()) {
                    String monthString = tmp.toString().toLowerCase();
                    Integer monthInt = MONTHS_MAP.get(monthString);

                    if (monthInt != null) {
                        month = monthInt;
                    } else {
                        try {
                            month = Integer.parseInt(monthString);
                        } catch (NumberFormatException nfExcptn) {
                            throw runtime.newArgumentError("Argument out of range.");
                        }
                    }
                } else {
                    month = (int) RubyNumeric.num2long(args[1]);
                }
            }
            if (1 > month || month > 12) {
                throw runtime.newArgumentError("Argument out of range: for month: " + month);
            }
        }

        int[] int_args = { 1, 0, 0, 0, 0, 0 };

        for (int i = 0; int_args.length >= i + 2; i++) {
            if (!args[i + 2].isNil()) {
                if (!(args[i + 2] instanceof RubyNumeric)) {
                    args[i + 2] = args[i + 2].callMethod(runtime.getCurrentContext(), "to_i");
                }

                long value = RubyNumeric.num2long(args[i + 2]);
                if (time_min[i] > value || value > time_max[i]) {
                    throw runtime.newArgumentError("argument out of range.");
                }
                int_args[i] = (int) value;
            }
        }

        if (0 <= year && year < 39) {
            year += 2000;
        } else if (69 <= year && year < 139) {
            year += 1900;
        }

        DateTimeZone dtz;
        if (gmt) {
            dtz = DateTimeZone.UTC;
        } else {
            dtz = getLocalTimeZone(runtime);
        }

        DateTime dt;
        // set up with min values and then add to allow rolling over
        try {
            dt = new DateTime(year, 1, 1, 0, 0, 0, 0, dtz);

            dt = dt.plusMonths(month - 1).plusDays(int_args[0] - 1).plusHours(int_args[1]).plusMinutes(int_args[2])
                    .plusSeconds(int_args[3]);
        } catch (org.joda.time.IllegalFieldValueException e) {
            throw runtime.newArgumentError("time out of range");
        }

        RubyTime time = new RubyTime(runtime, (RubyClass) recv, dt);
        // Ignores usec if 8 args (for compatibility with parsedate) or if not supplied.
        if (args.length != 8 && !args[6].isNil()) {
            int usec = int_args[4] % 1000;
            int msec = int_args[4] / 1000;

            if (int_args[4] < 0) {
                msec -= 1;
                usec += 1000;
            }
            time.dt = dt.withMillis(dt.getMillis() + msec);
            time.setUSec(usec);
        }

        time.callInit(IRubyObject.NULL_ARRAY, Block.NULL_BLOCK);
        return time;
    }

From source file:org.jruby.RubyTime.java

License:LGPL

private static RubyTime createTime(IRubyObject recv, IRubyObject[] args, boolean gmt, boolean utcOffset) {
    Ruby runtime = recv.getRuntime();//from  w w  w  .  j ava  2 s.  c  om
    int len = ARG_SIZE;
    boolean isDst = false;
    boolean setTzRelative = false;
    long nanos = 0;

    DateTimeZone dtz;
    if (gmt) {
        dtz = DateTimeZone.UTC;
    } else if (args.length == 10 && args[9] instanceof RubyString) {
        if (utcOffset) {
            dtz = getTimeZoneFromUtcOffset(runtime, args[9]);
            setTzRelative = true;
        } else {
            dtz = getTimeZoneFromString(runtime, args[9].toString());
        }
    } else if (args.length == 10 && args[9].respondsTo("to_int")) {
        IRubyObject offsetInt = args[9].callMethod(runtime.getCurrentContext(), "to_int");
        dtz = getTimeZone(runtime, ((RubyNumeric) offsetInt).getLongValue());
    } else {
        dtz = getLocalTimeZone(runtime);
    }

    if (args.length == 10) {
        if (args[8] instanceof RubyBoolean)
            isDst = args[8].isTrue();

        args = new IRubyObject[] { args[5], args[4], args[3], args[2], args[1], args[0], runtime.getNil() };
    } else {
        // MRI accepts additional wday argument which appears to be ignored.
        len = args.length;

        if (len < ARG_SIZE) {
            IRubyObject[] newArgs = new IRubyObject[ARG_SIZE];
            System.arraycopy(args, 0, newArgs, 0, args.length);
            for (int i = len; i < ARG_SIZE; i++) {
                newArgs[i] = runtime.getNil();
            }
            args = newArgs;
            len = ARG_SIZE;
        }
    }

    if (args[0] instanceof RubyString) {
        args[0] = RubyNumeric.str2inum(runtime, (RubyString) args[0], 10, false);
    }

    int year = (int) RubyNumeric.num2long(args[0]);
    int month = 1;

    if (len > 1) {
        if (!args[1].isNil()) {
            IRubyObject tmp = args[1].checkStringType();
            if (!tmp.isNil()) {
                String monthString = tmp.toString().toLowerCase();
                Integer monthInt = MONTHS_MAP.get(monthString);

                if (monthInt != null) {
                    month = monthInt;
                } else {
                    try {
                        month = Integer.parseInt(monthString);
                    } catch (NumberFormatException nfExcptn) {
                        throw runtime.newArgumentError("Argument out of range.");
                    }
                }
            } else {
                month = (int) RubyNumeric.num2long(args[1]);
            }
        }
        if (1 > month || month > 12) {
            throw runtime.newArgumentError("Argument out of range: for month: " + month);
        }
    }

    int[] int_args = { 1, 0, 0, 0, 0, 0 };

    for (int i = 0; int_args.length >= i + 2; i++) {
        if (!args[i + 2].isNil()) {
            if (!(args[i + 2] instanceof RubyNumeric)) {
                if (args[i + 2].respondsTo("to_int")) {
                    args[i + 2] = args[i + 2].callMethod(runtime.getCurrentContext(), "to_int");
                } else {
                    args[i + 2] = args[i + 2].callMethod(runtime.getCurrentContext(), "to_i");
                }
            }

            int_args[i] = RubyNumeric.num2int(args[i + 2]);
        }
    }

    // Validate the times
    // Complying with MRI behavior makes it a little bit complicated. Logic copied from:
    // https://github.com/ruby/ruby/blob/trunk/time.c#L2609
    if ((int_args[0] < 1 || int_args[0] > 31) || (int_args[1] < 0 || int_args[1] > 24)
            || (int_args[1] == 24 && (int_args[2] > 0 || int_args[3] > 0))
            || (int_args[2] < 0 || int_args[2] > 59) || (int_args[3] < 0 || int_args[3] > 60)) {
        throw runtime.newArgumentError("argument out of range.");
    }

    DateTime dt;
    // set up with min values and then add to allow rolling over
    try {
        dt = new DateTime(year, 1, 1, 0, 0, 0, 0, DateTimeZone.UTC);

        dt = dt.plusMonths(month - 1).plusDays(int_args[0] - 1).plusHours(int_args[1]).plusMinutes(int_args[2])
                .plusSeconds(int_args[3]);

        // 1.9 will observe fractional seconds *if* not given usec
        if (!args[5].isNil() && args[6].isNil()) {
            double secs = RubyFloat.num2dbl(args[5]);
            int int_millis = (int) (secs * 1000) % 1000;
            dt = dt.plusMillis(int_millis);
            nanos = ((long) (secs * 1000000000) % 1000000);
        }

        dt = dt.withZoneRetainFields(dtz);

        // If we're at a DST boundary, we need to choose the correct side of the boundary
        if (isDst) {
            final DateTime beforeDstBoundary = dt.withEarlierOffsetAtOverlap();
            final DateTime afterDstBoundary = dt.withLaterOffsetAtOverlap();

            final int offsetBeforeBoundary = dtz.getOffset(beforeDstBoundary);
            final int offsetAfterBoundary = dtz.getOffset(afterDstBoundary);

            // If the time is during DST, we need to pick the time with the highest offset
            dt = offsetBeforeBoundary > offsetAfterBoundary ? beforeDstBoundary : afterDstBoundary;
        }
    } catch (org.joda.time.IllegalFieldValueException e) {
        throw runtime.newArgumentError("time out of range");
    }

    RubyTime time = new RubyTime(runtime, (RubyClass) recv, dt);
    // Ignores usec if 8 args (for compatibility with parsedate) or if not supplied.
    if (args.length != 8 && !args[6].isNil()) {
        boolean fractionalUSecGiven = args[6] instanceof RubyFloat || args[6] instanceof RubyRational;

        if (fractionalUSecGiven) {
            double micros = RubyNumeric.num2dbl(args[6]);
            time.dt = dt.withMillis(dt.getMillis() + (long) (micros / 1000));
            nanos = ((long) (micros * 1000) % 1000000);
        } else {
            int usec = int_args[4] % 1000;
            int msec = int_args[4] / 1000;

            if (int_args[4] < 0) {
                msec -= 1;
                usec += 1000;
            }
            time.dt = dt.withMillis(dt.getMillis() + msec);
            time.setUSec(usec);
        }
    }

    if (nanos != 0)
        time.setNSec(nanos);

    time.callInit(IRubyObject.NULL_ARRAY, Block.NULL_BLOCK);
    time.setIsTzRelative(setTzRelative);
    return time;
}

From source file:org.kairosdb.util.Util.java

License:Apache License

/**
 Computes the duration of the sampling (value * unit) starting at timestamp.
        /*from ww  w .ja v a2s.c om*/
 @param timestamp unix timestamp of the start time.
 @return the duration of the sampling in millisecond.
 */
public static long getSamplingDuration(long timestamp, Sampling sampling, DateTimeZone timeZone) {
    long ret = sampling.getValue();
    DateTime dt = new DateTime(timestamp, timeZone);
    switch (sampling.getUnit()) {
    case YEARS:
        ret = new org.joda.time.Duration(dt, dt.plusYears((int) sampling.getValue())).getMillis();
        break;
    case MONTHS:
        ret = new org.joda.time.Duration(dt, dt.plusMonths((int) sampling.getValue())).getMillis();
        break;
    case WEEKS:
        ret = new org.joda.time.Duration(dt, dt.plusWeeks((int) sampling.getValue())).getMillis();
        break;
    case DAYS:
        ret = new org.joda.time.Duration(dt, dt.plusDays((int) sampling.getValue())).getMillis();
        break;
    case HOURS:
        ret = new org.joda.time.Duration(dt, dt.plusHours((int) sampling.getValue())).getMillis();
        break;
    case MINUTES:
        ret = new org.joda.time.Duration(dt, dt.plusMinutes((int) sampling.getValue())).getMillis();
        break;
    case SECONDS:
        ret = new org.joda.time.Duration(dt, dt.plusSeconds((int) sampling.getValue())).getMillis();
        break;
    case MILLISECONDS:
        ret = (long) sampling.getValue();
        break;
    }
    return ret;
}

From source file:org.killbill.billing.subscription.alignment.BaseAligner.java

License:Apache License

private DateTime addOrRemoveDuration(final DateTime input, final Duration duration, boolean add) {
    DateTime result = input;
    switch (duration.getUnit()) {
    case DAYS:// w w  w.jav a  2  s  . com
        result = add ? result.plusDays(duration.getNumber()) : result.minusDays(duration.getNumber());
        ;
        break;

    case MONTHS:
        result = add ? result.plusMonths(duration.getNumber()) : result.minusMonths(duration.getNumber());
        break;

    case YEARS:
        result = add ? result.plusYears(duration.getNumber()) : result.minusYears(duration.getNumber());
        break;
    case UNLIMITED:
    default:
        throw new RuntimeException("Trying to move to unlimited time period");
    }
    return result;
}