Example usage for org.joda.time Days daysIn

List of usage examples for org.joda.time Days daysIn

Introduction

In this page you can find the example usage for org.joda.time Days daysIn.

Prototype

public static Days daysIn(ReadableInterval interval) 

Source Link

Document

Creates a Days representing the number of whole days in the specified interval.

Usage

From source file:ca.barrenechea.ticker.utils.TimeUtils.java

License:Apache License

public static TimeSpan getSpan(long start, long end) {
    if (end <= start) {
        return new TimeSpan(0, 0, 0);
    }/*from ww  w . j a v a 2  s  .  c o m*/

    Interval interval = new Interval(start, end);

    Days days = Days.daysIn(interval);
    Hours hours = Hours.hoursIn(interval).minus(days.toStandardHours());
    Minutes minutes = Minutes.minutesIn(interval).minus(days.toStandardMinutes())
            .minus(hours.toStandardMinutes());

    return new TimeSpan(days.getDays(), hours.getHours(), minutes.getMinutes());
}

From source file:com.cisco.dvbu.ps.utils.date.DateDiffTimestamp.java

License:Open Source License

/**
 * Called to invoke the stored procedure.  Will only be called a
 * single time per instance.  Can throw CustomProcedureException or
 * SQLException if there is an error during invoke.
 *///  w  ww.  java  2s  . c o m
public void invoke(Object[] inputValues) throws CustomProcedureException, SQLException {
    Timestamp startTimestamp = null;
    Timestamp endTimestamp = null;
    Calendar startCal = null;
    Calendar endCal = null;
    DateTime startDateTime = null;
    DateTime endDateTime = null;
    String datePart = null;
    long dateLength = 0;

    try {
        result = null;
        if (inputValues[0] == null) {
            result = new Long(dateLength);
            return;
        }

        if (inputValues[1] == null) {
            result = new Long(dateLength);
            return;
        }

        if (inputValues[2] == null) {
            result = new Long(dateLength);
            return;
        }

        datePart = (String) inputValues[0];
        startTimestamp = (Timestamp) inputValues[1];
        // long startMilliseconds = startTimestamp.getTime() +
        // (startTimestamp.getNanos() / 1000000);
        long startMilliseconds = startTimestamp.getTime()
                + (startTimestamp.getNanos() % 1000000L >= 500000L ? 1 : 0);
        startCal = Calendar.getInstance();
        startCal.setTimeInMillis(startMilliseconds);

        endTimestamp = (Timestamp) inputValues[2];
        // long endMilliseconds = endTimestamp.getTime() +
        // (endTimestamp.getNanos() / 1000000);
        long endMilliseconds = endTimestamp.getTime() + (endTimestamp.getNanos() % 1000000L >= 500000L ? 1 : 0);

        endCal = Calendar.getInstance();
        endCal.setTimeInMillis(endMilliseconds);

        startDateTime = new DateTime(startCal.get(Calendar.YEAR), startCal.get(Calendar.MONTH) + 1,
                startCal.get(Calendar.DAY_OF_MONTH), startCal.get(Calendar.HOUR_OF_DAY),
                startCal.get(Calendar.MINUTE), startCal.get(Calendar.SECOND),
                startCal.get(Calendar.MILLISECOND));
        endDateTime = new DateTime(endCal.get(Calendar.YEAR), endCal.get(Calendar.MONTH) + 1,
                endCal.get(Calendar.DAY_OF_MONTH), endCal.get(Calendar.HOUR_OF_DAY),
                endCal.get(Calendar.MINUTE), endCal.get(Calendar.SECOND), endCal.get(Calendar.MILLISECOND));

        Interval interval = new Interval(startDateTime, endDateTime);

        if (datePart.equalsIgnoreCase("second") || datePart.equalsIgnoreCase("ss")) {
            Seconds seconds = Seconds.secondsIn(interval);
            dateLength = seconds.getSeconds();
        } else if (datePart.equalsIgnoreCase("minute") || datePart.equalsIgnoreCase("mi")) {
            Minutes minutes = Minutes.minutesIn(interval);
            dateLength = minutes.getMinutes();
        } else if (datePart.equalsIgnoreCase("hour") || datePart.equalsIgnoreCase("hh")) {
            Hours hours = Hours.hoursIn(interval);
            dateLength = hours.getHours();
        } else if (datePart.equalsIgnoreCase("day") || datePart.equalsIgnoreCase("dd")) {
            Days days = Days.daysIn(interval);
            dateLength = days.getDays();
        } else if (datePart.equalsIgnoreCase("week") || datePart.equalsIgnoreCase("wk")) {
            Weeks weeks = Weeks.weeksIn(interval);
            dateLength = weeks.getWeeks();
        } else if (datePart.equalsIgnoreCase("month") || datePart.equalsIgnoreCase("mm")) {
            Months months = Months.monthsIn(interval);
            dateLength = months.getMonths();
        } else if (datePart.equalsIgnoreCase("year") || datePart.equalsIgnoreCase("yy")) {
            Years years = Years.yearsIn(interval);
            dateLength = years.getYears();
        } else if (datePart.equalsIgnoreCase("millisecond") || datePart.equalsIgnoreCase("ms")) {
            dateLength = (endTimestamp.getTime() - startTimestamp.getTime()); // millis
        } else if (datePart.equalsIgnoreCase("microsecond") || datePart.equalsIgnoreCase("mcs")) {
            dateLength = ((endTimestamp.getTime() - startTimestamp.getTime()) / 1000) // seconds
                    * 1000000L // micros
                    + (endTimestamp.getNanos() - startTimestamp.getNanos()) / 1000; // nanos/1000
        } else if (datePart.equalsIgnoreCase("nanosecond") || datePart.equalsIgnoreCase("ns")) {
            dateLength = ((endTimestamp.getTime() - startTimestamp.getTime()) / 1000) // seconds
                    * 1000000000L // nanos
                    + (endTimestamp.getNanos() - startTimestamp.getNanos()); // nanos
        } else {
            throw new IllegalArgumentException(datePart);
        }

        result = new Long(dateLength);

    } catch (Throwable t) {
        throw new CustomProcedureException(t);
    }
}

From source file:com.manydesigns.portofino.calendar.AbstractMonth.java

License:Open Source License

public AbstractMonth(DateMidnight referenceDateMidnight) {
    logger.debug("Initializing month");
    this.referenceDateMidnight = referenceDateMidnight;
    logger.debug("Reference date midnight: {}", referenceDateMidnight);

    monthStart = referenceDateMidnight.withDayOfMonth(1);
    monthEnd = monthStart.plusMonths(1);
    monthInterval = new Interval(monthStart, monthEnd);
    logger.debug("Month interval: {}", monthInterval);

    daysCount = Days.daysIn(monthInterval).getDays();
    logger.debug("Initializing {} days", daysCount);

    days = createDaysArray(daysCount);//from   w  w  w  .j  a  v  a2s . co m
    DateMidnight dayStart = monthStart;
    for (int i = 0; i < daysCount; i++) {
        DateMidnight dayEnd = dayStart.plusDays(1);
        days[i] = createDay(dayStart, dayEnd);

        // advance to next day
        dayStart = dayEnd;
    }
}

From source file:com.stagecents.pay.domain.PayCycle.java

License:Open Source License

/**
 * Returns the number of elapsed days in this pay cycle including the given
 * time interval./*  ww w  .ja v a2  s  .co m*/
 * 
 * @param arg The given time interval
 * @return The number of days since the beginning of this pay cycle,
 *         inclusive of the given time interval.
 */
private int getCycleDays(Interval arg) {
    return Days.daysIn(arg.withStart(getWeeklyCycleStart(arg))).getDays();
}

From source file:de.iteratec.iteraplan.model.RuntimePeriod.java

License:Open Source License

/**
 * @return Returns the gap to the given period in days or -1 if there is no gap. If the given
 *         period is {@code null} (i.e. {@link BaseDateUtils#MIN_DATE} and {@link BaseDateUtils#MAX_DATE}
 *         is assumed), the test returns -1.
 *///from  w  ww .  j a v a2 s  .com
public int gapToPeriod(RuntimePeriod period) {

    if (period == null) {
        return -1;
    }

    Interval other = DateUtils.asInterval(period.getStart(), period.getEnd());
    Interval gap = asInterval().gap(other);
    return gap == null ? -1 : Days.daysIn(gap).getDays();
}

From source file:net.schweerelos.timeline.model.Timeline.java

License:Open Source License

private void recalculate() {
    if (start == null || end == null) {
        logger.warn("recalculating aborted, start and/or end is null");
        numSlices = 0;/*from  ww w. j a  v  a  2  s . com*/
        return;
    }
    Interval interval = new Interval(start, end);

    if (Years.yearsIn(interval).isGreaterThan(Years.ZERO)) {
        // make it start at the start of the current increment mode
        start = start.withDayOfYear(start.dayOfYear().getMinimumValue());
        end = end.withDayOfYear(end.dayOfYear().getMaximumValue());
        interval = new Interval(start, end);

        // figure out number of slices
        numSlices = Years.yearsIn(interval).getYears();
        if (start.plusYears(numSlices).isBefore(end)) {
            numSlices += 1;
        }

        // update label extractor
        sliceLabelExtractor = new SliceLabelExtractor() {
            @Override
            public String extractLabel(DateTime from) {
                return from.year().getAsShortText();
            }
        };

        // update increment
        increment = Years.ONE.toPeriod();
        incrementMode = Mode.Years;
    } else if (Months.monthsIn(interval).isGreaterThan(Months.ZERO)) {
        // make it start at the start of the current increment mode
        start = start.withDayOfMonth(start.dayOfMonth().getMinimumValue());
        end = end.withDayOfMonth(end.dayOfMonth().getMaximumValue());
        interval = new Interval(start, end);

        numSlices = Months.monthsIn(interval).getMonths();
        if (start.plusMonths(numSlices).isBefore(end)) {
            numSlices += 1;
        }

        sliceLabelExtractor = new SliceLabelExtractor() {
            @Override
            public String extractLabel(DateTime from) {
                return from.monthOfYear().getAsShortText();
            }
        };

        increment = Months.ONE.toPeriod();
        incrementMode = Mode.Months;
    } else if (Weeks.weeksIn(interval).isGreaterThan(Weeks.ZERO)) {
        start = start.withDayOfWeek(start.dayOfWeek().getMinimumValue());
        end = end.withDayOfWeek(end.dayOfWeek().getMaximumValue());
        interval = new Interval(start, end);

        numSlices = Weeks.weeksIn(interval).getWeeks();
        if (start.plusWeeks(numSlices).isBefore(end)) {
            numSlices += 1;
        }

        sliceLabelExtractor = new SliceLabelExtractor() {
            @Override
            public String extractLabel(DateTime from) {
                return "W" + from.weekOfWeekyear().getAsShortText();
            }
        };

        increment = Weeks.ONE.toPeriod();
        incrementMode = Mode.Weeks;
    } else {
        numSlices = Days.daysIn(interval).getDays();
        if (start.plusDays(numSlices).isBefore(end)) {
            numSlices += 1;
        }
        if (numSlices == 0) {
            // force at least one day to be drawn
            numSlices = 1;
        }

        sliceLabelExtractor = new SliceLabelExtractor() {
            @Override
            public String extractLabel(DateTime from) {
                return from.dayOfMonth().getAsShortText();
            }
        };

        increment = Days.ONE.toPeriod();
        incrementMode = Mode.Days;
    }

    // reset time of day too
    start = start.withMillisOfDay(start.millisOfDay().getMinimumValue());
    end = end.withMillisOfDay(end.millisOfDay().getMaximumValue());

    // recalculate which intervals are within range
    intervalsWithinRange.clear();
    intervalsWithinRange.addAll(calculateIntervalsWithinRange(start, end));

    // notify listeners
    changeSupport.firePropertyChange(INTERVAL_PROPERTY_KEY, interval, new Interval(start, end));
}

From source file:org.ash.history.CalendarH.java

License:Open Source License

/**
 * Get fragged days for Calendar.//from  ww w . j  a  v a 2 s  .co m
 * 
 * @param begin0
 * @param end0
 * @return
 */
private long[] getFraggedDays(long begin0, long end0) {

    DateTime begin = new DateTime(begin0);
    DateTime end = new DateTime(end0);

    DateTime beginTmp = new DateTime(begin);
    DateTime beginDayPlus0000 = new DateTime(beginTmp.getYear(), beginTmp.getMonthOfYear(),
            beginTmp.getDayOfMonth(), 0, 0, 0, 0);
    DateTime endTmp = new DateTime(end);
    DateTime endPlus2359 = new DateTime(endTmp.getYear(), endTmp.getMonthOfYear(), endTmp.getDayOfMonth(), 23,
            59, 59, 999);

    Interval interval = new Interval(beginDayPlus0000, endPlus2359);
    Days days = Days.daysIn(interval);

    int daysBetween = days.getDays();

    long[] flaggedDates = new long[daysBetween + 1];

    DateTime tmp = new DateTime(begin);
    // Load days.
    for (int i = 0; i <= daysBetween; i++) {
        DateTime tmp1 = tmp.plusDays(i);
        flaggedDates[i] = tmp1.getMillis();
    }

    return flaggedDates;
}

From source file:org.ash.history.MainPreview.java

License:Open Source License

/**
 * Set date format for x Axis and range data.
 * /*www.j  a  v a 2s.c  om*/
 * @param databaseHistory
 */
private void setDateFormatXAxis(long start, long end) {

    DateFormat dateFormatDate = new SimpleDateFormat("d");
    DateFormat dateFormatMonth = new SimpleDateFormat("MM");
    DateFormat dateFormatData = new SimpleDateFormat("dd.MM.yyyy");

    if ((dateFormatDate.format(start).equalsIgnoreCase(dateFormatDate.format(end)))
            && (dateFormatMonth.format(start).equalsIgnoreCase(dateFormatMonth.format(end)))) {
        setDateFormatXAxis("HH:mm");
        setRangeData(dateFormatData.format(start));
    } else {
        DateTime startTemp = new DateTime(start);
        DateTime endTemp = new DateTime(end);
        Interval interval = new Interval(startTemp, endTemp);
        Days days = Days.daysIn(interval);

        if (days.getDays() < 2) {
            setDateFormatXAxis("HH:mm");
            setRangeData(dateFormatData.format(start) + "-" + dateFormatData.format(end));
        } else {
            setDateFormatXAxis("EEE d, HH");
            setRangeData(dateFormatData.format(start) + "-" + dateFormatData.format(end));
        }
    }
}

From source file:org.sleuthkit.autopsy.timeline.utils.RangeDivisionInfo.java

License:Open Source License

/**
 * Static factory method.//www  .  j  a  v  a2s. c om
 *
 * Determine the period size, number of periods, whole period bounds, and
 * formatters to use to visualize the given timerange.
 *
 * @param timeRange
 *
 * @return
 */
public static RangeDivisionInfo getRangeDivisionInfo(Interval timeRange) {
    //Check from largest to smallest unit

    //TODO: make this more generic... reduce code duplication -jm
    DateTimeFieldType timeUnit;
    final DateTime startWithZone = timeRange.getStart().withZone(TimeLineController.getJodaTimeZone());
    final DateTime endWithZone = timeRange.getEnd().withZone(TimeLineController.getJodaTimeZone());

    if (Years.yearsIn(timeRange).isGreaterThan(Years.THREE)) {
        timeUnit = DateTimeFieldType.year();
        long lower = startWithZone.property(timeUnit).roundFloorCopy().getMillis();
        long upper = endWithZone.property(timeUnit).roundCeilingCopy().getMillis();
        return new RangeDivisionInfo(timeRange, Years.yearsIn(timeRange).get(timeUnit.getDurationType()) + 1,
                TimeUnits.YEARS, ISODateTimeFormat.year(), lower, upper);
    } else if (Months.monthsIn(timeRange).isGreaterThan(Months.THREE)) {
        timeUnit = DateTimeFieldType.monthOfYear();
        long lower = startWithZone.property(timeUnit).roundFloorCopy().getMillis();
        long upper = endWithZone.property(timeUnit).roundCeilingCopy().getMillis();
        return new RangeDivisionInfo(timeRange, Months.monthsIn(timeRange).getMonths() + 1, TimeUnits.MONTHS,
                DateTimeFormat.forPattern("YYYY'-'MMMM"), lower, upper); // NON-NLS
    } else if (Days.daysIn(timeRange).isGreaterThan(Days.THREE)) {
        timeUnit = DateTimeFieldType.dayOfMonth();
        long lower = startWithZone.property(timeUnit).roundFloorCopy().getMillis();
        long upper = endWithZone.property(timeUnit).roundCeilingCopy().getMillis();
        return new RangeDivisionInfo(timeRange, Days.daysIn(timeRange).getDays() + 1, TimeUnits.DAYS,
                DateTimeFormat.forPattern("YYYY'-'MMMM'-'dd"), lower, upper); // NON-NLS
    } else if (Hours.hoursIn(timeRange).isGreaterThan(Hours.THREE)) {
        timeUnit = DateTimeFieldType.hourOfDay();
        long lower = startWithZone.property(timeUnit).roundFloorCopy().getMillis();
        long upper = endWithZone.property(timeUnit).roundCeilingCopy().getMillis();
        return new RangeDivisionInfo(timeRange, Hours.hoursIn(timeRange).getHours() + 1, TimeUnits.HOURS,
                DateTimeFormat.forPattern("YYYY'-'MMMM'-'dd HH"), lower, upper); // NON-NLS
    } else if (Minutes.minutesIn(timeRange).isGreaterThan(Minutes.THREE)) {
        timeUnit = DateTimeFieldType.minuteOfHour();
        long lower = startWithZone.property(timeUnit).roundFloorCopy().getMillis();
        long upper = endWithZone.property(timeUnit).roundCeilingCopy().getMillis();
        return new RangeDivisionInfo(timeRange, Minutes.minutesIn(timeRange).getMinutes() + 1,
                TimeUnits.MINUTES, DateTimeFormat.forPattern("YYYY'-'MMMM'-'dd HH':'mm"), lower, upper); // NON-NLS
    } else {
        timeUnit = DateTimeFieldType.secondOfMinute();
        long lower = startWithZone.property(timeUnit).roundFloorCopy().getMillis();
        long upper = endWithZone.property(timeUnit).roundCeilingCopy().getMillis();
        return new RangeDivisionInfo(timeRange, Seconds.secondsIn(timeRange).getSeconds() + 1,
                TimeUnits.SECONDS, DateTimeFormat.forPattern("YYYY'-'MMMM'-'dd HH':'mm':'ss"), lower, upper); // NON-NLS
    }
}