Example usage for org.joda.time DateTime dayOfMonth

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

Introduction

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

Prototype

public Property dayOfMonth() 

Source Link

Document

Get the day of month property which provides access to advanced functionality.

Usage

From source file:com.phloc.datetime.PDTUtils.java

License:Apache License

/**
 * Get the start- and end-week numbers for the passed year and month.
 *
 * @param aDT//from   ww w  .  j a va2  s.c  om
 *        The object to use year and month from.
 * @return A non-<code>null</code> pair where the first item is the initial
 *         week number, and the second item is the month's last week number.
 */
@Nonnull
public static IReadonlyPair<Integer, Integer> getWeeksOfMonth(@Nonnull final DateTime aDT) {
    final int nStart = aDT.withDayOfMonth(1).getWeekOfWeekyear();
    final int nEnd = aDT.withDayOfMonth(aDT.dayOfMonth().getMaximumValue()).getWeekOfWeekyear();
    return ReadonlyPair.create(Integer.valueOf(nStart), Integer.valueOf(nEnd));
}

From source file:com.qcadoo.localization.api.utils.DateUtils.java

License:Open Source License

private static DateTime roundUpDate(final DateTime dateTime, final String dateExpressionPart) {
    DateTime roundedDate = dateTime;
    final String[] date = dateExpressionPart.split("-");
    if (date.length < 3 || StringUtils.isBlank(date[2])) {
        final int day = roundedDate.dayOfMonth().getMaximumValue();
        roundedDate = roundedDate.withDayOfMonth(day);
    }//from www .j a va 2  s  .  c  o  m
    if (date.length < 2 || StringUtils.isBlank(date[1])) {
        roundedDate = roundedDate.withMonthOfYear(12);
    }
    return roundedDate;
}

From source file:com.sap.dirigible.runtime.metrics.TimeUtils.java

License:Open Source License

private static DateTime dateTimeCeiling(DateTime dt, Period p) {
    if (p.getYears() != 0) {
        return dt.yearOfEra().roundCeilingCopy().minusYears(dt.getYearOfEra() % p.getYears());
    } else if (p.getMonths() != 0) {
        return dt.monthOfYear().roundCeilingCopy().minusMonths((dt.getMonthOfYear() - 1) % p.getMonths());
    } else if (p.getWeeks() != 0) {
        return dt.weekOfWeekyear().roundCeilingCopy().minusWeeks((dt.getWeekOfWeekyear() - 1) % p.getWeeks());
    } else if (p.getDays() != 0) {
        return dt.dayOfMonth().roundCeilingCopy().minusDays((dt.getDayOfMonth() - 1) % p.getDays());
    } else if (p.getHours() != 0) {
        return dt.hourOfDay().roundCeilingCopy().minusHours(dt.getHourOfDay() % p.getHours());
    } else if (p.getMinutes() != 0) {
        return dt.minuteOfHour().roundCeilingCopy().minusMinutes(dt.getMinuteOfHour() % p.getMinutes());
    } else if (p.getSeconds() != 0) {
        return dt.secondOfMinute().roundCeilingCopy().minusSeconds(dt.getSecondOfMinute() % p.getSeconds());
    }// w w  w .ja  va 2 s.  c  o m
    return dt.millisOfSecond().roundCeilingCopy().minusMillis(dt.getMillisOfSecond() % p.getMillis());
}

From source file:com.smict.person.data.DoctorData.java

/**
 * Add doctor's workday depend on month pattern.
 * @author anubissmile/*from   w  w  w  .j  a  v  a  2  s.c o m*/
 * @param DoctorModel docModel
 * @param DoctTimeModel docTimeModel
 * @return int rec | Count of record that get affected.
 */
public int addDoctorWorkdayPattern(DoctorModel docModel, DoctTimeModel docTimeModel) {
    DateUtil dt = new DateUtil();
    int key = 0;
    String[] workMonth;
    List<String> insertVal = new ArrayList<String>();
    DateTime firstOfMonth, endOfMonth, nowDate;
    DateTimeFormatter dayName = DateTimeFormat.forPattern("E");
    DateTimeFormatter fullDateTime = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
    DateTimeFormatter fullDate = DateTimeFormat.forPattern("yyyy-MM-dd");
    String day, fullDay;
    String startDateTime, endDateTime;
    int workMinutes;

    /**
     * Loop month.
     */
    for (String month : docTimeModel.getWork_month()) {
        /**
         * Convert BE. to AD.
         */
        workMonth = month.split("-");
        workMonth[1] = String.valueOf(Integer.parseInt(workMonth[1]) - 543);

        /**
         * Make first date of month.
         */
        nowDate = firstOfMonth = DateTime.parse(workMonth[1] + "-" + workMonth[0] + "-" + "01");
        System.out.println(firstOfMonth);

        /**
         * Find Maximum date of month.   
         */
        endOfMonth = firstOfMonth.dayOfMonth().withMaximumValue();
        System.out.println(endOfMonth);

        /**
         * Loop day
         */
        while (Days.daysBetween(nowDate, endOfMonth).getDays() >= 0) {
            /**
             * Get day name.
             */
            day = dayName.print(nowDate);
            fullDay = fullDate.print(nowDate);
            System.out.print(day.concat(" | "));
            System.out.print(fullDay.concat(" | "));
            System.out.println(nowDate);

            /**
             * Fetch time range by day
             */
            //Mon
            // ('1', '2017-06-01 05:23:24', '2017-06-01 15:23:24', '25', '431', '0', '0000-00-00 00:00:01', '0000-00-00 00:00:01')
            if ((day.equals("Mon") || day.equals("."))
                    && (!docTimeModel.getTime_in_mon().get(key).equals("00:00")
                            || !docTimeModel.getTime_out_mon().get(key).equals("00:00"))) {
                workMinutes = Minutes.minutesBetween(LocalTime.parse(docTimeModel.getTime_in_mon().get(key)),
                        LocalTime.parse(docTimeModel.getTime_out_mon().get(key))).getMinutes();
                startDateTime = fullDate.print(nowDate).toString().concat(" ")
                        .concat(docTimeModel.getTime_in_mon().get(key)).concat(":00");
                endDateTime = fullDate.print(nowDate).toString().concat(" ")
                        .concat(docTimeModel.getTime_out_mon().get(key)).concat(":00");
                insertVal.add(" ('" + docModel.getDoctorID() + "', '" + startDateTime + "', '" + endDateTime
                        + "', '" + workMinutes + "', '" + docModel.getBranch_id()
                        + "', '0', '1', '0000-00-00 00:00:01', '0000-00-00 00:00:01') ");
                nowDate = nowDate.plusDays(1);
                continue;
            }

            //Tue
            if ((day.equals("Tue") || day.equals("."))
                    && (!docTimeModel.getTime_in_tue().get(key).equals("00:00")
                            || !docTimeModel.getTime_out_tue().get(key).equals("00:00"))) {
                workMinutes = Minutes.minutesBetween(LocalTime.parse(docTimeModel.getTime_in_tue().get(key)),
                        LocalTime.parse(docTimeModel.getTime_out_tue().get(key))).getMinutes();
                startDateTime = fullDate.print(nowDate).toString().concat(" ")
                        .concat(docTimeModel.getTime_in_tue().get(key)).concat(":00");
                endDateTime = fullDate.print(nowDate).toString().concat(" ")
                        .concat(docTimeModel.getTime_out_tue().get(key)).concat(":00");
                insertVal.add(" ('" + docModel.getDoctorID() + "', '" + startDateTime + "', '" + endDateTime
                        + "', '" + workMinutes + "', '" + docModel.getBranch_id()
                        + "', '0', '1', '0000-00-00 00:00:01', '0000-00-00 00:00:01') ");
                nowDate = nowDate.plusDays(1);
                continue;
            }

            //Wed
            if ((day.equals("Wed") || day.equals("."))
                    && (!docTimeModel.getTime_in_wed().get(key).equals("00:00")
                            || !docTimeModel.getTime_out_wed().get(key).equals("00:00"))) {
                workMinutes = Minutes.minutesBetween(LocalTime.parse(docTimeModel.getTime_in_wed().get(key)),
                        LocalTime.parse(docTimeModel.getTime_out_wed().get(key))).getMinutes();
                startDateTime = fullDate.print(nowDate).toString().concat(" ")
                        .concat(docTimeModel.getTime_in_wed().get(key)).concat(":00");
                endDateTime = fullDate.print(nowDate).toString().concat(" ")
                        .concat(docTimeModel.getTime_out_wed().get(key)).concat(":00");
                insertVal.add(" ('" + docModel.getDoctorID() + "', '" + startDateTime + "', '" + endDateTime
                        + "', '" + workMinutes + "', '" + docModel.getBranch_id()
                        + "', '0', '1', '0000-00-00 00:00:01', '0000-00-00 00:00:01') ");
                nowDate = nowDate.plusDays(1);
                continue;
            }

            //Thu
            if ((day.equals("Thu") || day.equals("."))
                    && (!docTimeModel.getTime_in_thu().get(key).equals("00:00")
                            || !docTimeModel.getTime_out_thu().get(key).equals("00:00"))) {
                workMinutes = Minutes.minutesBetween(LocalTime.parse(docTimeModel.getTime_in_thu().get(key)),
                        LocalTime.parse(docTimeModel.getTime_out_thu().get(key))).getMinutes();
                startDateTime = fullDate.print(nowDate).toString().concat(" ")
                        .concat(docTimeModel.getTime_in_thu().get(key)).concat(":00");
                endDateTime = fullDate.print(nowDate).toString().concat(" ")
                        .concat(docTimeModel.getTime_out_thu().get(key)).concat(":00");
                insertVal.add(" ('" + docModel.getDoctorID() + "', '" + startDateTime + "', '" + endDateTime
                        + "', '" + workMinutes + "', '" + docModel.getBranch_id()
                        + "', '0', '1', '0000-00-00 00:00:01', '0000-00-00 00:00:01') ");
                nowDate = nowDate.plusDays(1);
                continue;
            }

            //Fri
            if ((day.equals("Fri") || day.equals("."))
                    && (!docTimeModel.getTime_in_fri().get(key).equals("00:00")
                            || !docTimeModel.getTime_out_fri().get(key).equals("00:00"))) {
                workMinutes = Minutes.minutesBetween(LocalTime.parse(docTimeModel.getTime_in_fri().get(key)),
                        LocalTime.parse(docTimeModel.getTime_out_fri().get(key))).getMinutes();
                startDateTime = fullDate.print(nowDate).toString().concat(" ")
                        .concat(docTimeModel.getTime_in_fri().get(key)).concat(":00");
                endDateTime = fullDate.print(nowDate).toString().concat(" ")
                        .concat(docTimeModel.getTime_out_fri().get(key)).concat(":00");
                insertVal.add(" ('" + docModel.getDoctorID() + "', '" + startDateTime + "', '" + endDateTime
                        + "', '" + workMinutes + "', '" + docModel.getBranch_id()
                        + "', '0', '1', '0000-00-00 00:00:01', '0000-00-00 00:00:01') ");
                nowDate = nowDate.plusDays(1);
                continue;
            }

            //Sat
            if ((day.equals("Sat") || day.equals("."))
                    && (!docTimeModel.getTime_in_sat().get(key).equals("00:00")
                            || !docTimeModel.getTime_out_sat().get(key).equals("00:00"))) {
                workMinutes = Minutes.minutesBetween(LocalTime.parse(docTimeModel.getTime_in_sat().get(key)),
                        LocalTime.parse(docTimeModel.getTime_out_sat().get(key))).getMinutes();
                startDateTime = fullDate.print(nowDate).toString().concat(" ")
                        .concat(docTimeModel.getTime_in_sat().get(key)).concat(":00");
                endDateTime = fullDate.print(nowDate).toString().concat(" ")
                        .concat(docTimeModel.getTime_out_sat().get(key)).concat(":00");
                insertVal.add(" ('" + docModel.getDoctorID() + "', '" + startDateTime + "', '" + endDateTime
                        + "', '" + workMinutes + "', '" + docModel.getBranch_id()
                        + "', '0', '1', '0000-00-00 00:00:01', '0000-00-00 00:00:01') ");
                nowDate = nowDate.plusDays(1);
                continue;
            }

            //Sun
            if ((day.equals("Sun") || day.equals("."))
                    && (!docTimeModel.getTime_in_sun().get(key).equals("00:00")
                            || !docTimeModel.getTime_out_sun().get(key).equals("00:00"))) {
                workMinutes = Minutes.minutesBetween(LocalTime.parse(docTimeModel.getTime_in_sun().get(key)),
                        LocalTime.parse(docTimeModel.getTime_out_sun().get(key))).getMinutes();
                startDateTime = fullDate.print(nowDate).toString().concat(" ")
                        .concat(docTimeModel.getTime_in_sun().get(key)).concat(":00");
                endDateTime = fullDate.print(nowDate).toString().concat(" ")
                        .concat(docTimeModel.getTime_out_sun().get(key)).concat(":00");
                insertVal.add(" ('" + docModel.getDoctorID() + "', '" + startDateTime + "', '" + endDateTime
                        + "', '" + workMinutes + "', '" + docModel.getBranch_id()
                        + "', '0', '1', '0000-00-00 00:00:01', '0000-00-00 00:00:01') ");
                nowDate = nowDate.plusDays(1);
                continue;
            }

            /**
             * Plus one day.
             */
            nowDate = nowDate.plusDays(1);
        }

        ++key;
    }

    String SQL = StringUtils.join(insertVal, ", ");
    SQL = "INSERT INTO `doctor_workday` " + "(`doctor_id`, `start_datetime`, " + "`end_datetime`, `work_hour`, "
            + "`branch_id`, `branch_room_id`, " + "`checkin_status`, `checkin_datetime`, `checkout_datetime`) "
            + "VALUES ".concat(SQL);

    agent.connectMySQL();
    agent.begin();
    int rec = agent.exeUpdate(SQL);
    agent.commit();
    agent.disconnectMySQL();

    return rec;
}

From source file:com.sonicle.webtop.calendar.Service.java

License:Open Source License

public void processPrintScheduler(HttpServletRequest request, HttpServletResponse response) {
    ByteArrayOutputStream baos = null;
    UserProfile up = getEnv().getProfile();

    try {/*  ww  w  .ja v a  2 s.com*/
        String filename = ServletUtils.getStringParameter(request, "filename", "print");
        String view = ServletUtils.getStringParameter(request, "view", "w5");
        String from = ServletUtils.getStringParameter(request, "startDate", true);

        DateTime startDate = DateTimeUtils.parseYmdHmsWithZone(from, "00:00:00", up.getTimeZone());

        ReportConfig.Builder builder = reportConfigBuilder();
        DateTime fromDate = null, toDate = null;
        AbstractAgenda rpt = null;
        if (view.equals("d")) {
            fromDate = startDate.withTimeAtStartOfDay();
            toDate = startDate.plusDays(1).withTimeAtStartOfDay();
            rpt = new RptAgendaSummary(builder.build(), 1);

        } else if (view.equals("w5")) {
            fromDate = startDate.withTimeAtStartOfDay();
            toDate = startDate.plusDays(5).withTimeAtStartOfDay();
            rpt = new RptAgendaWeek5(builder.build());

        } else if (view.equals("w")) {
            fromDate = startDate.withTimeAtStartOfDay();
            toDate = startDate.plusDays(7).withTimeAtStartOfDay();
            rpt = new RptAgendaWeek7(builder.build());

        } else if (view.equals("dw")) {
            fromDate = startDate.withTimeAtStartOfDay();
            toDate = startDate.plusDays(14).withTimeAtStartOfDay();
            rpt = new RptAgendaSummary(builder.build(), 14);

        } else if (view.equals("m")) {
            if (startDate.getDayOfMonth() == 1) {
                fromDate = startDate.withTimeAtStartOfDay();
            } else {
                fromDate = startDate.plusMonths(1).withDayOfMonth(1).withTimeAtStartOfDay();
            }
            int days = fromDate.dayOfMonth().getMaximumValue();
            toDate = fromDate.plusMonths(1).withDayOfMonth(1).withTimeAtStartOfDay();
            rpt = new RptAgendaSummary(builder.build(), days);

        } else {
            throw new WTException("View not supported [{0}]", view);
        }

        Set<Integer> activeCalIds = getActiveFolderIds();
        Map<Integer, Calendar> calendars = folders.entrySet().stream()
                .filter(map -> activeCalIds.contains(map.getKey()))
                .collect(Collectors.toMap(map -> map.getKey(), map -> map.getValue().getCalendar()));

        List<SchedEventInstance> instances = manager.listEventInstances(activeCalIds,
                new DateTimeRange(fromDate, toDate), up.getTimeZone(), true);
        rpt.setDataSource(manager, fromDate, toDate, up.getTimeZone(), calendars, instances);

        baos = new ByteArrayOutputStream();
        WT.generateReportToStream(rpt, AbstractReport.OutputType.PDF, baos);
        ServletUtils.setContentDispositionHeader(response, "inline", filename + ".pdf");
        ServletUtils.writeContent(response, baos, "application/pdf");

    } catch (Exception ex) {
        logger.error("Error in PrintScheduler", ex);
        ServletUtils.writeErrorHandlingJs(response, ex.getMessage());
    } finally {
        IOUtils.closeQuietly(baos);
    }
}

From source file:com.splicemachine.db.iapi.types.TruncateFunctionUtil.java

License:Apache License

private static DateTimeDataValue doTrunc(DataValueDescriptor dateVal, DataValueDescriptor truncValue,
        DateTimeDataValue truncd, boolean isTimestamp) throws StandardException {
    if (dateVal.isNull()) {
        return truncd;
    }// w w  w .  j  a v  a2s.  c  o  m
    DateTime realDT = dateVal.getDateTime();
    DateTime newDT;
    // DateTime(int year, int monthOfYear, int dayOfMonth, int hourOfDay, int minuteOfHour, int secondOfMinute, int millisOfSecond)
    switch (getTruncValue(truncValue)) {
    case YEAR:
    case YR:
        newDT = realDT.year().roundFloorCopy();
        break;

    case MONTH:
    case MON:
    case MO:
        newDT = realDT.monthOfYear().roundFloorCopy();
        break;

    case DAY:
        newDT = realDT.dayOfMonth().roundFloorCopy();
        break;

    case HOUR:
    case HR:
        if (!isTimestamp) {
            throw StandardException.newException(SQLState.LANG_TRUNCATE_WRONG_TRUNC_VALUE_FOR_DATE,
                    getTruncValue(truncValue).name());
        }
        newDT = realDT.hourOfDay().roundFloorCopy();
        break;

    case MINUTE:
    case MIN:
        if (!isTimestamp) {
            throw StandardException.newException(SQLState.LANG_TRUNCATE_WRONG_TRUNC_VALUE_FOR_DATE,
                    getTruncValue(truncValue).name());
        }
        newDT = realDT.minuteOfHour().roundFloorCopy();
        break;

    case SECOND:
    case SEC:
        if (!isTimestamp) {
            throw StandardException.newException(SQLState.LANG_TRUNCATE_WRONG_TRUNC_VALUE_FOR_DATE,
                    getTruncValue(truncValue).name());
        }
        newDT = realDT.secondOfMinute().roundFloorCopy();
        break;

    case MILLISECOND:
    case MILLI:
        if (!isTimestamp) {
            throw StandardException.newException(SQLState.LANG_TRUNCATE_WRONG_TRUNC_VALUE_FOR_DATE,
                    getTruncValue(truncValue).name());
        }
        newDT = realDT;
        break;

    default:
        throw StandardException.newException(SQLState.LANG_TRUNCATE_UNKNOWN_TRUNC_VALUE,
                (isTimestamp ? "TIMESTAMP" : "DATE"), getTruncValue(truncValue),
                stringifyValues(DateTruncValue.values()));
    }
    truncd.setValue(newDT);
    return truncd;
}

From source file:com.squarespace.template.plugins.PluginDateUtils.java

License:Apache License

public static boolean sameDay(long instant1, long instant2, String tzName) {
    DateTimeZone zone = null;/*w w w .j  a va  2 s.  c  o  m*/
    try {
        zone = DateTimeZone.forID(tzName);
    } catch (IllegalArgumentException e) {
        zone = DateTimeZone.getDefault();
    }
    DateTime date1 = new DateTime(instant1, zone);
    DateTime date2 = new DateTime(instant2, zone);
    return (date1.year().get() == date2.year().get())
            && (date1.monthOfYear().get() == date2.monthOfYear().get())
            && (date1.dayOfMonth().get() == date2.dayOfMonth().get());
}

From source file:com.squarespace.template.plugins.PluginDateUtils.java

License:Apache License

/**
 * Takes a strftime()-compatible format string and outputs the properly formatted date.
 *//*w w w .j a v a2  s  .  c  o m*/
public static void formatDate(Locale locale, String fmt, long instant, String tzName, StringBuilder buf) {
    DateTimeZone zone = null;
    try {
        zone = DateTimeZone.forID(tzName);
    } catch (IllegalArgumentException e) {
        zone = DateTimeZone.getDefault();
    }
    DateTime date = new DateTime(instant, zone);
    int index = 0;
    int len = fmt.length();
    while (index < len) {
        char c1 = fmt.charAt(index);
        index++;
        if (c1 != '%' || index == len) {
            buf.append(c1);
            continue;
        }
        char c2 = fmt.charAt(index);
        switch (c2) {
        case 'A':
            buf.append(date.dayOfWeek().getAsText(locale));
            break;
        case 'a':
            buf.append(date.dayOfWeek().getAsShortText(locale));
            break;
        case 'B':
            buf.append(date.monthOfYear().getAsText(locale));
            break;
        case 'b':
            buf.append(date.monthOfYear().getAsShortText(locale));
            break;
        case 'C':
            leftPad(date.centuryOfEra().get(), '0', 2, buf);
            break;
        case 'c':
            formatAggregate(DateTimeAggregate.FULL, locale, date, buf);
            break;
        case 'D':
            formatAggregate(DateTimeAggregate.MMDDYY, locale, date, buf);
            break;
        case 'd':
            leftPad(date.dayOfMonth().get(), '0', 2, buf);
            break;
        case 'e':
            leftPad(date.dayOfMonth().get(), ' ', 2, buf);
            break;
        case 'F':
            formatAggregate(DateTimeAggregate.YYYYMMDD, locale, date, buf);
            break;
        case 'G':
            buf.append(date.year().get());
            break;
        case 'g':
            leftPad(date.yearOfCentury().get(), '0', 2, buf);
            break;
        case 'H':
            leftPad(date.hourOfDay().get(), '0', 2, buf);
            break;
        case 'h':
            buf.append(date.monthOfYear().getAsShortText(locale));
            break;
        case 'I':
            leftPad(date.get(DateTimeFieldType.clockhourOfHalfday()), '0', 2, buf);
            break;
        case 'j':
            leftPad(date.dayOfYear().get(), '0', 3, buf);
            break;
        case 'k':
            leftPad(date.get(DateTimeFieldType.clockhourOfDay()), ' ', 2, buf);
            break;
        case 'l':
            leftPad(date.get(DateTimeFieldType.clockhourOfHalfday()), ' ', 2, buf);
            break;
        case 'M':
            leftPad(date.minuteOfHour().get(), '0', 2, buf);
            break;
        case 'm':
            leftPad(date.monthOfYear().get(), '0', 2, buf);
            break;
        case 'n':
            buf.append('\n');
            break;
        case 'P':
            buf.append(date.get(DateTimeFieldType.halfdayOfDay()) == 0 ? "am" : "pm");
            break;
        case 'p':
            buf.append(date.get(DateTimeFieldType.halfdayOfDay()) == 0 ? "AM" : "PM");
            break;
        case 'R':
            formatAggregate(DateTimeAggregate.H240_M0, locale, date, buf);
            break;
        case 'S':
            leftPad(date.secondOfMinute().get(), '0', 2, buf);
            break;
        case 's':
            buf.append(instant / 1000);
            break;
        case 't':
            buf.append('\t');
            break;
        case 'T':
            // Equivalent of %H:%M:%S
            formatAggregate(DateTimeAggregate.H240_M0, locale, date, buf);
            buf.append(':');
            leftPad(date.secondOfMinute().get(), '0', 2, buf);
            break;

        case 'U':
            // TODO: fix week-of-year number
            leftPad(date.weekOfWeekyear().get(), '0', 2, buf);
            break;

        case 'u':
            buf.append(date.dayOfWeek().get());
            break;

        case 'V':
            // TODO: fix week-of-year number
            leftPad(date.weekOfWeekyear().get(), '0', 2, buf);
            break;

        case 'v':
            // Equivalent of %e-%b-%Y
            leftPad(date.dayOfMonth().get(), ' ', 2, buf);
            buf.append('-');
            buf.append(date.monthOfYear().getAsShortText());
            buf.append('-');
            buf.append(date.getYear());
            break;

        case 'W':
            // TODO: fix week-of-year number
            break;

        case 'w':
            buf.append(date.dayOfWeek().get());
            break;
        case 'X':
            formatAggregate(DateTimeAggregate.HHMMSSP, locale, date, buf);
            break;
        case 'x':
            formatAggregate(DateTimeAggregate.MMDDYYYY, locale, date, buf);
            break;
        case 'Y':
            buf.append(date.getYear());
            break;
        case 'y':
            leftPad(date.getYearOfCentury(), '0', 2, buf);
            break;

        case 'Z':
            // Note: Joda's nameKey happens to be the same as the shortName. Making
            // this change to workaround Joda https://github.com/JodaOrg/joda-time/issues/288
            buf.append(zone.getNameKey(date.getMillis()));
            break;

        case 'z':
            int offset = date.getZone().getOffset(instant) / 60000;
            int hours = (int) Math.floor(offset / 60);
            int minutes = (hours * 60) - offset;
            if (offset < 0) {
                buf.append('-');
            }
            leftPad(Math.abs(hours), '0', 2, buf);
            leftPad(Math.abs(minutes), '0', 2, buf);
            break;

        default:
            // no match, emit literals.
            buf.append(c1).append(c2);
        }
        index++;
    }
}

From source file:com.squarespace.template.plugins.PluginDateUtils.java

License:Apache License

private static void formatAggregate(DateTimeAggregate type, Locale locale, DateTime date, StringBuilder buf) {
    switch (type) {
    case FULL:/*from  w w  w.  ja v  a 2  s  .  co  m*/
        buf.append(date.dayOfWeek().getAsShortText(locale));
        buf.append(' ');
        leftPad(date.dayOfMonth().get(), '0', 2, buf);
        buf.append(' ');
        buf.append(date.monthOfYear().getAsShortText(locale));
        buf.append(' ');
        buf.append(date.year().get());
        buf.append(' ');
        leftPad(date.get(DateTimeFieldType.clockhourOfHalfday()), '0', 2, buf);
        buf.append(':');
        leftPad(date.minuteOfHour().get(), '0', 2, buf);
        buf.append(':');
        leftPad(date.secondOfMinute().get(), '0', 2, buf);
        buf.append(' ');
        buf.append(date.get(DateTimeFieldType.halfdayOfDay()) == 0 ? "AM" : "PM");
        buf.append(' ');
        buf.append(date.getZone().getNameKey(date.getMillis()));
        break;

    case H240_M0:
        leftPad(date.get(DateTimeFieldType.clockhourOfDay()), '0', 2, buf);
        buf.append(':');
        leftPad(date.minuteOfHour().get(), '0', 2, buf);
        break;

    case HHMMSSP:
        leftPad(date.get(DateTimeFieldType.hourOfHalfday()), '0', 2, buf);
        buf.append(':');
        leftPad(date.getMinuteOfHour(), '0', 2, buf);
        buf.append(':');
        leftPad(date.getSecondOfMinute(), '0', 2, buf);
        buf.append(' ');
        buf.append(date.get(DateTimeFieldType.halfdayOfDay()) == 0 ? "AM" : "PM");
        break;

    case MMDDYY:
        leftPad(date.getMonthOfYear(), '0', 2, buf);
        buf.append('/');
        leftPad(date.dayOfMonth().get(), '0', 2, buf);
        buf.append('/');
        leftPad(date.yearOfCentury().get(), '0', 2, buf);
        break;

    case MMDDYYYY:
        leftPad(date.getMonthOfYear(), '0', 2, buf);
        buf.append('/');
        leftPad(date.dayOfMonth().get(), '0', 2, buf);
        buf.append('/');
        buf.append(date.getYear());
        break;

    case YYYYMMDD:
        buf.append(date.year().get());
        buf.append('-');
        leftPad(date.monthOfYear().get(), '0', 2, buf);
        buf.append('-');
        leftPad(date.dayOfMonth().get(), '0', 2, buf);
        break;

    default:
        break;
    }
}

From source file:com.squid.kraken.v4.core.analysis.engine.processor.AnalysisCompute.java

License:Open Source License

private IntervalleObject alignPastInterval(IntervalleObject presentInterval, IntervalleObject pastInterval,
        Axis joinAxis) throws ScopeException {

    if (joinAxis != null && presentInterval != null && pastInterval != null) {

        Object lowerPresent = presentInterval.getLowerBound();
        Object lowerPast = pastInterval.getLowerBound();
        Object upperPresent = presentInterval.getUpperBound();
        Object upperPast = pastInterval.getUpperBound();
        ///*from www  .  j  ava2 s.c  om*/
        IDomain image = joinAxis.getDefinition().getImageDomain();
        if (lowerPresent instanceof Date && lowerPast instanceof Date) {

            DateTime lowerPastDT = new DateTime((Date) lowerPast);
            DateTime lowerPresentDT = new DateTime((Date) lowerPresent);
            DateTime upperPresentDT = new DateTime((Date) upperPresent);
            DateTime upperPastDT = new DateTime((Date) upperPast);

            // realign
            if (image.isInstanceOf(IDomain.YEARLY)) {
                // check if present is an exact number of years
                if (lowerPresentDT.getDayOfYear() == 1
                        && upperPresentDT.getDayOfYear() == upperPresentDT.dayOfYear().getMaximumValue()) {
                    // check of both periods have the same number of days
                    Period presentPeriod = new Period(new LocalDate(lowerPresent),
                            (new LocalDate(upperPresent)), PeriodType.days());
                    Period pastPeriod = new Period(new LocalDate(lowerPast), (new LocalDate(upperPast)),
                            PeriodType.days());
                    if (presentPeriod.getDays() == pastPeriod.getDays()) {
                        presentPeriod = new Period(new LocalDate(lowerPresent),
                                (new LocalDate(upperPresent)).plusDays(1), PeriodType.years());
                        pastPeriod = new Period(new LocalDate(lowerPast),
                                (new LocalDate(upperPast)).plusDays(1), PeriodType.years());

                        // realign
                        if (presentPeriod.getYears() > pastPeriod.getYears()) {
                            // some days are missing to align the periods
                            if (lowerPastDT.getDayOfYear() != 1) {
                                // previous period
                                Date newLowerPast = new DateTime(upperPastDT.getYear(), 1, 1, 0, 0).toDate();
                                return new IntervalleObject(newLowerPast, upperPast);
                            }
                            if (upperPastDT.getDayOfYear() != upperPastDT.dayOfYear().getMaximumValue()) {
                                // year over year
                                Date newUpperPast = new DateTime(upperPastDT.getYear(), 12, 31, 23, 59)
                                        .toDate();
                                return new IntervalleObject(lowerPast, newUpperPast);
                            }
                        } else {
                            // either already aligned, or some days should
                            // be removed

                            if (upperPastDT.getDayOfYear() != upperPastDT.dayOfYear().getMaximumValue()) {
                                // year over Year
                                Date newUpperPast = new DateTime(upperPastDT.getYear() - 1, 12, 31, 23, 59)
                                        .toDate();
                                return new IntervalleObject(lowerPast, newUpperPast);

                            }
                            if (lowerPastDT.getDayOfYear() != 1) {
                                // previous period
                                Date newLowerPast = new DateTime(lowerPastDT.getYear() + 1, 1, 1, 0, 0)
                                        .toDate();
                                return new IntervalleObject(newLowerPast, upperPast);
                            }

                        }
                    }
                }
            } else if (image.isInstanceOf(IDomain.QUATERLY) || image.isInstanceOf(IDomain.MONTHLY)) {
                // check if present is an exact number of month
                if (lowerPresentDT.getDayOfMonth() == 1
                        && upperPresentDT.getDayOfMonth() == upperPresentDT.dayOfMonth().getMaximumValue()) {
                    // check of both periods have the same number of days
                    Period presentPeriod = new Period(new LocalDate(lowerPresent), new LocalDate(upperPresent),
                            PeriodType.days());
                    Period pastPeriod = new Period(new LocalDate(lowerPast), new LocalDate(upperPast),
                            PeriodType.days());
                    if (presentPeriod.getDays() == pastPeriod.getDays()) {
                        // realign
                        presentPeriod = new Period(new LocalDate(lowerPresent),
                                (new LocalDate(upperPresent)).plusDays(1), PeriodType.months());
                        pastPeriod = new Period(new LocalDate(lowerPast),
                                (new LocalDate(upperPast)).plusDays(1), PeriodType.months());
                        if (presentPeriod.getMonths() > pastPeriod.getMonths()) {
                            // some days are missing

                            if (upperPastDT.getDayOfMonth() != upperPastDT.dayOfMonth().getMaximumValue()) {
                                // month over month
                                Date newUpperPast = new DateTime(upperPastDT.getYear(),
                                        upperPastDT.getMonthOfYear(),
                                        upperPastDT.dayOfMonth().getMaximumValue(), 23, 59).toDate();
                                return new IntervalleObject(lowerPast, newUpperPast);
                            }

                            if (lowerPastDT.getDayOfMonth() != 1) {
                                // previous period
                                Date newLowerPast = new DateTime(lowerPastDT.getYear(),
                                        lowerPastDT.getMonthOfYear(), 1, 0, 0).toDate();
                                return new IntervalleObject(newLowerPast, upperPast);

                            }

                        } else {
                            // either already aligned, of some days should
                            // be removed
                            if (upperPastDT.getDayOfMonth() != upperPastDT.dayOfMonth().getMaximumValue()) {
                                /// month over month
                                if (upperPastDT.getMonthOfYear() == 1) {
                                    Date newUpperPast = new DateTime(upperPastDT.getYear() - 1, 12, 31, 23, 59)
                                            .toDate();
                                    return new IntervalleObject(lowerPast, newUpperPast);

                                } else {

                                    upperPastDT = upperPastDT.minusMonths(1);
                                    Date newUpperPast = new DateTime(upperPastDT.getYear(),
                                            upperPastDT.getMonthOfYear(),
                                            upperPastDT.dayOfMonth().getMaximumValue(), 23, 59).toDate();
                                    return new IntervalleObject(lowerPast, newUpperPast);
                                }
                            }
                            if (lowerPastDT.getDayOfMonth() != 1) {
                                // previous period
                                if (lowerPastDT.getMonthOfYear() == 12) {
                                    Date newLowerPast = new DateTime(lowerPastDT.getYear() + 1, 1, 1, 0, 0)
                                            .toDate();
                                    return new IntervalleObject(newLowerPast, upperPast);

                                } else {
                                    lowerPastDT = lowerPastDT.plusMonths(1);
                                    Date newLowerPast = new DateTime(lowerPastDT.getYear(),
                                            lowerPastDT.getMonthOfYear(), 1, 0, 0).toDate();
                                    return new IntervalleObject(newLowerPast, upperPast);

                                }

                            }

                        }
                    }
                }
            }
        }
    }
    return pastInterval;
}