Example usage for org.joda.time DateTime getMonthOfYear

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

Introduction

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

Prototype

public int getMonthOfYear() 

Source Link

Document

Get the month of year field value.

Usage

From source file:org.jtotus.database.LocalJDBC.java

License:Open Source License

public double[] fetchPeriod(String tableName, DateTime startDate, DateTime endDate, String type) {
    BigDecimal retValue = null;/*from   w  ww. ja  va  2 s .  c om*/
    PreparedStatement pstm = null;
    java.sql.Date retDate = null;
    ResultSet results = null;
    ArrayList<Double> closingPrices = new ArrayList<Double>(600);
    Connection connection = null;

    try {
        String query = "SELECT " + type + ", DATE FROM " + this.normTableName(tableName)
                + " WHERE DATE>=? AND DATE<=? ORDER BY DATE ASC";
        // this.createTable(connection, this.normTableName(tableName));

        connection = this.getConnection();
        pstm = connection.prepareStatement(query, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);

        java.sql.Date startSqlDate = new java.sql.Date(startDate.getMillis());
        pstm.setDate(1, startSqlDate);

        java.sql.Date endSqlDate = new java.sql.Date(endDate.getMillis());
        pstm.setDate(2, endSqlDate);

        DateIterator dateIter = new DateIterator(startDate, endDate);

        results = pstm.executeQuery();
        DateTime dateCheck;

        if (debug) {
            System.out.printf("start data %s end date: %s\n", startSqlDate.toString(), endSqlDate.toString());
        }

        while (dateIter.hasNext()) {
            dateCheck = dateIter.nextInCalendar();

            if (results.next()) {
                retValue = results.getBigDecimal(1);
                retDate = results.getDate(2);

                DateTime compCal = new DateTime(retDate.getTime());
                if (compCal.getDayOfMonth() == dateCheck.getDayOfMonth()
                        && compCal.getMonthOfYear() == dateCheck.getMonthOfYear()
                        && compCal.getYear() == dateCheck.getYear()) {
                    closingPrices.add(retValue.doubleValue());
                    continue;
                } else {
                    results.previous();
                }
            }

            BigDecimal failOverValue = getFetcher().fetchData(tableName, dateCheck, type);
            if (failOverValue != null) {
                closingPrices.add(failOverValue.doubleValue());
            }
        }

    } catch (SQLException ex) {
        System.err.printf("LocalJDBC Unable to find date for:'%s' from'%s' Time" + startDate.toDate() + "\n",
                "Cosing Price", tableName);
        ex.printStackTrace();
        SQLException xp = null;
        while ((xp = ex.getNextException()) != null) {
            xp.printStackTrace();
        }

    } finally {
        try {
            if (results != null)
                results.close();
            if (pstm != null)
                pstm.close();
            if (connection != null)
                connection.close();
            //                System.out.printf("Max connect:%d in use:%d\n",mainPool.getMaxConnections(), mainPool.getActiveConnections());
            //                mainPool.dispose();

        } catch (SQLException ex) {
            Logger.getLogger(LocalJDBC.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    return ArrayUtils.toPrimitive(closingPrices.toArray(new Double[0]));
}

From source file:org.jtotus.database.LocalJDBC.java

License:Open Source License

public HashMap<String, Double> fetchPeriodAsMap(String tableName, DateTime startDate, DateTime endDate) {

    HashMap<String, Double> retMap = new HashMap<String, Double>();
    BigDecimal retValue = null;//from   w w  w . ja va  2  s  .  c  o m
    PreparedStatement pstm = null;
    java.sql.Date retDate = null;
    ResultSet results = null;
    Connection connection = null;

    try {
        String query = "SELECT CLOSE, DATE FROM " + this.normTableName(tableName)
                + " WHERE DATE>=? AND DATE<=? ORDER BY DATE ASC";
        // this.createTable(connection, this.normTableName(tableName));

        connection = this.getConnection();
        pstm = connection.prepareStatement(query);

        java.sql.Date startSqlDate = new java.sql.Date(startDate.getMillis());
        pstm.setDate(1, startSqlDate);

        java.sql.Date endSqlDate = new java.sql.Date(endDate.getMillis());
        pstm.setDate(2, endSqlDate);

        System.out.printf("fetchPeriod : %s : %s\n", startSqlDate, endSqlDate);
        DateIterator iter = new DateIterator(startDate, endDate);
        results = pstm.executeQuery();
        DateTime dateCheck;

        while (results.next()) {
            retValue = results.getBigDecimal(1);
            retDate = results.getDate(2);

            if (retValue == null || retDate == null) {
                System.err.println("Database is corrupted!");
                System.exit(-1);
            }

            if (iter.hasNext()) {
                dateCheck = iter.nextInCalendar();

                DateTime compCal = new DateTime(retDate.getTime());

                if (debug) {
                    if (retValue != null) {
                        System.out.printf("Fetched:\'%s\' from \'%s\' : value:%f date:%s\n", "Closing Price",
                                tableName, retValue.doubleValue(), retDate.toString());
                    } else {
                        System.out.printf("Fetched:\'%s\' from \'%s\' : value:%s date:%s\n", "Closing Price",
                                tableName, "is null", retDate.toString());
                    }
                }

                if (compCal.getDayOfMonth() == dateCheck.getDayOfMonth()
                        && compCal.getMonthOfYear() == dateCheck.getMonthOfYear()
                        && compCal.getYear() == dateCheck.getYear()) {
                    retMap.put(formatter.print(compCal), retValue.doubleValue());
                    continue;
                }

                while (((compCal.getDayOfMonth() != dateCheck.getDayOfMonth())
                        || (compCal.getMonthOfYear() != dateCheck.getMonthOfYear())
                        || (compCal.getYear() != dateCheck.getYear())) && dateCheck.isBefore(compCal)) {
                    if (fetcher != null) {
                        BigDecimal failOverValue = getFetcher().fetchData(tableName, dateCheck, "CLOSE");
                        if (failOverValue != null) {
                            retMap.put(formatter.print(dateCheck), retValue.doubleValue());
                        }

                        if (iter.hasNext()) {
                            System.err.printf("Warning : Miss matching dates for: %s - %s\n",
                                    retDate.toString(), dateCheck.toString());
                            dateCheck = iter.nextInCalendar();
                            continue;
                        }
                    } else {
                        System.err.printf("Fatal missing fetcher : Miss matching dates: %s - %s\n",
                                retDate.toString(), dateCheck.toString());
                        return null;
                    }
                }
            }
        }

        while (iter.hasNext()) {
            retValue = getFetcher().fetchData(tableName, iter.nextInCalendar(), "CLOSE");
            if (retValue != null) {
                retMap.put(formatter.print(iter.getCurrentAsCalendar()), retValue.doubleValue());
            }
        }

    } catch (SQLException ex) {
        System.err.printf("LocalJDBC Unable to find date for:'%s' from'%s' Time" + startDate.toDate() + "\n",
                "Cosing Price", tableName);
        //            ex.printStackTrace();
        //            SQLException xp = null;
        //            while((xp = ex.getNextException()) != null) {
        //                xp.printStackTrace();
        //            }

    } finally {
        try {
            if (results != null)
                results.close();
            if (pstm != null)
                pstm.close();
            if (connection != null)
                connection.close();
            //                System.out.printf("Max connect:%d in use:%d\n",mainPool.getMaxConnections(), mainPool.getActiveConnections());
            //                mainPool.dispose();

        } catch (SQLException ex) {
            Logger.getLogger(LocalJDBC.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    return retMap;
}

From source file:org.kemri.wellcome.dhisreport.api.utils.QuarterlyPeriod.java

License:Open Source License

/**
 * TODO: Probably more efficient ways to do this. But this is least cryptic
 * @param date /*from w w w.ja v  a  2s  .c  o m*/
 */
public QuarterlyPeriod(Date date) {
    DateTime dt = new DateTime(date);
    int monthNum = dt.getMonthOfYear();
    if (monthNum >= 1 && monthNum <= 3) {
        startDate = dt.withMonthOfYear(DateTimeConstants.JANUARY).dayOfMonth().withMinimumValue().toDate();
        endDate = dt.withMonthOfYear(DateTimeConstants.MARCH).dayOfMonth().withMaximumValue()
                .withTime(23, 59, 59, 999).toDate();
    } else if (monthNum >= 4 && monthNum <= 6) {
        startDate = dt.withMonthOfYear(DateTimeConstants.APRIL).dayOfMonth().withMinimumValue().toDate();
        endDate = dt.withMonthOfYear(DateTimeConstants.JUNE).dayOfMonth().withMaximumValue()
                .withTime(23, 59, 59, 999).toDate();
    } else if (monthNum >= 7 && monthNum <= 9) {
        startDate = dt.withMonthOfYear(DateTimeConstants.JULY).dayOfMonth().withMinimumValue().toDate();
        endDate = dt.withMonthOfYear(DateTimeConstants.SEPTEMBER).dayOfMonth().withMaximumValue()
                .withTime(23, 59, 59, 999).toDate();
    } else if (monthNum >= 10 && monthNum <= 12) {
        startDate = dt.withMonthOfYear(DateTimeConstants.OCTOBER).dayOfMonth().withMinimumValue().toDate();
        endDate = dt.withMonthOfYear(DateTimeConstants.DECEMBER).dayOfMonth().withMaximumValue()
                .withTime(23, 59, 59, 999).toDate();
    }
}

From source file:org.kemri.wellcome.dhisreport.api.utils.QuarterlyPeriod.java

License:Open Source License

@Override
public String getAsIsoString() {
    DateTime dt = new DateTime(getStart());
    return dt.getYear() + "Q" + ((dt.getMonthOfYear() / 3) + 1);
}

From source file:org.kitesdk.apps.examples.report.ScheduledReportJob.java

License:Apache License

public void run() {

    // TODO: Switch to parameterized views.
    View<ExampleEvent> view = Datasets.load(ScheduledReportApp.EXAMPLE_DS_URI, ExampleEvent.class);

    RefinableView<GenericRecord> target = Datasets.load(ScheduledReportApp.REPORT_DS_URI, GenericRecord.class);

    // Get the view into which this report will be written.
    DateTime dateTime = getNominalTime().toDateTime(DateTimeZone.UTC);

    View<GenericRecord> output = target.with("year", dateTime.getYear())
            .with("month", dateTime.getMonthOfYear()).with("day", dateTime.getDayOfMonth())
            .with("hour", dateTime.getHourOfDay()).with("minute", dateTime.getMinuteOfHour());

    Pipeline pipeline = getPipeline();/*from  w  w  w. j ava 2s. co  m*/

    PCollection<ExampleEvent> events = pipeline.read(CrunchDatasets.asSource(view));

    PTable<Long, ExampleEvent> eventsByUser = events.by(new GetEventId(), Avros.longs());

    // Count of events by user ID.
    PTable<Long, Long> userEventCounts = eventsByUser.keys().count();

    PCollection<GenericData.Record> report = userEventCounts.parallelDo(new ToUserReport(),
            Avros.generics(SCHEMA));

    pipeline.write(report, CrunchDatasets.asTarget(output));

    pipeline.run();
}

From source file:org.kuali.kpme.core.leaveplan.service.LeavePlanServiceImpl.java

License:Educational Community License

@Override
public boolean isFirstCalendarPeriodOfLeavePlan(CalendarEntry calendarEntry, String leavePlan,
        LocalDate asOfDate) {// ww  w.j a va  2  s  . c  om
    boolean isFirstCalendarPeriodOfLeavePlan = false;

    LeavePlan leavePlanObj = getLeavePlan(leavePlan, asOfDate);

    if (leavePlanObj != null) {
        DateTime calendarEntryEndDate = calendarEntry.getBeginPeriodFullDateTime();

        int calendarYearStartMonth = Integer.valueOf(leavePlanObj.getCalendarYearStartMonth());
        int calendarYearStartDay = Integer.valueOf(leavePlanObj.getCalendarYearStartDayOfMonth());
        int calendarEntryEndDateMonth = calendarEntryEndDate.getMonthOfYear();
        int calendarEntryEndDateDay = calendarEntryEndDate.getDayOfMonth();

        isFirstCalendarPeriodOfLeavePlan = (calendarYearStartMonth == calendarEntryEndDateMonth)
                && (calendarYearStartDay == calendarEntryEndDateDay);
    }

    return isFirstCalendarPeriodOfLeavePlan;
}

From source file:org.kuali.kpme.core.leaveplan.service.LeavePlanServiceImpl.java

License:Educational Community License

@Override
public boolean isLastCalendarPeriodOfLeavePlan(CalendarEntry calendarEntry, String leavePlan,
        LocalDate asOfDate) {/* w  ww  .j  a  v a  2 s.c o m*/
    boolean isLastCalendarPeriodOfLeavePlan = false;

    LeavePlan leavePlanObj = getLeavePlan(leavePlan, asOfDate);

    if (leavePlanObj != null) {
        DateTime calendarEntryEndDate = calendarEntry.getEndPeriodFullDateTime();

        int calendarYearStartMonth = Integer.valueOf(leavePlanObj.getCalendarYearStartMonth());
        int calendarYearStartDay = Integer.valueOf(leavePlanObj.getCalendarYearStartDayOfMonth());
        int calendarEntryEndDateMonth = calendarEntryEndDate.getMonthOfYear();
        int calendarEntryEndDateDay = calendarEntryEndDate.getDayOfMonth();

        isLastCalendarPeriodOfLeavePlan = (calendarYearStartMonth == calendarEntryEndDateMonth)
                && (calendarYearStartDay == calendarEntryEndDateDay);
    }

    return isLastCalendarPeriodOfLeavePlan;
}

From source file:org.logstash.filters.parser.JodaParser.java

License:Apache License

private Instant parseAndGuessYear(DateTimeFormatter parser, String value) {
    // if we get here, we need to do some special handling at the time each event is handled
    // because things like the current year could be different, etc.
    DateTime dateTime;
    if (hasZone) {
        dateTime = parser.parseDateTime(value);
    } else {//  www .  j a va 2s  .c om
        dateTime = parser.withZoneUTC().parseLocalDateTime(value).toDateTime(parser.getZone());
    }

    // The time format we have has no year listed, so we'll have to guess the year.
    int month = dateTime.getMonthOfYear();
    DateTime now = clock.read();
    int eventYear;

    if (month == 12 && now.getMonthOfYear() == 1) {
        // Now is January, event is December. Assume it's from last year.
        eventYear = now.getYear() - 1;
    } else if (month == 1 && now.getMonthOfYear() == 12) {
        // Now is December, event is January. Assume it's from next year.
        eventYear = now.getYear() + 1;
    } else {
        // Otherwise, assume it's from this year.
        eventYear = now.getYear();
    }

    return dateTime.withYear(eventYear).toInstant();
}

From source file:org.mayocat.shop.front.context.DateContext.java

License:Mozilla Public License

public DateContext(Date date, Locale locale) {
    DateTime dt = new DateTime(date);

    shortDate = DateTimeFormat.shortDate().withLocale(locale).print(dt);
    longDate = DateTimeFormat.longDate().withLocale(locale).print(dt);

    dayOfMonth = dt.getDayOfMonth();/*from  www .j  a v a 2 s  .  c o m*/
    monthOfYear = dt.getMonthOfYear();
    year = dt.getYear();
    time = dt.toDate().getTime();
    dateTime = dt.toString();
}

From source file:org.medici.bia.controller.admin.EditUserController.java

License:Open Source License

/**
 * //w  w w.  ja va2 s.com
 * @param command
 * @param result
 * @return
 */
@RequestMapping(method = RequestMethod.GET)
public ModelAndView setupForm(@ModelAttribute("command") EditUserCommand command) {
    Map<String, Object> model = new HashMap<String, Object>(0);
    List<Month> months = null;
    User user = new User();

    try {
        months = getAdminService().getMonths();
        model.put("months", months);

        List<UserAuthority> authorities = getAdminService().getAuthorities();
        model.put("authorities", authorities);
    } catch (ApplicationThrowable ath) {
        return new ModelAndView("error/ShowDocument", model);
    }

    try {
        if (StringUtils.isNotBlank(command.getAccount())) {
            user = getAdminService().findUser(command.getAccount());

            if (user != null) {
                command.setAccount(user.getAccount());
                command.setOriginalAccount(user.getAccount());
                command.setFirstName(user.getFirstName());
                command.setMiddleName(user.getMiddleName());
                command.setLastName(user.getLastName());
                command.setPassword(user.getPassword());
                Iterator<UserRole> iterator = user.getUserRoles().iterator();
                List<String> userRoles = new ArrayList<String>(0);
                while (iterator.hasNext()) {
                    UserRole userRole = iterator.next();
                    userRoles.add(userRole.getUserAuthority().getAuthority().toString());
                }
                command.setUserRoles(userRoles);
                DateTime expirationUserDate = new DateTime(user.getExpirationDate());
                command.setYearExpirationUser(expirationUserDate.getYear());
                command.setMonthExpirationUser(new Month(expirationUserDate.getMonthOfYear()).getMonthNum());
                command.setDayExpirationUser(expirationUserDate.getDayOfMonth());
                DateTime expirationPasswordDate = new DateTime(user.getExpirationPasswordDate());
                command.setYearExpirationPassword(expirationPasswordDate.getYear());
                command.setMonthExpirationPassword(
                        new Month(expirationPasswordDate.getMonthOfYear()).getMonthNum());
                command.setDayExpirationPassword(expirationPasswordDate.getDayOfMonth());

                command.setActive(user.getActive());
                command.setApproved(user.getApproved());
                command.setLocked(user.getLocked());
            }
        } else {
            // If account is blank, flow manage create new account
            command.setAccount("");
            command.setFirstName("");
            command.setLastName("");
            command.setPassword("");

            // Default user role is GUEST
            List<String> userRoles = new ArrayList<String>(0);
            userRoles.add(UserAuthority.Authority.COMMUNITY_USERS.toString());
            command.setUserRoles(userRoles);

            Integer expirationUserMonth = NumberUtils
                    .toInt(ApplicationPropertyManager.getApplicationProperty("user.expiration.user.months"));
            DateTime expirationUserDate = (new DateTime()).plusMonths(expirationUserMonth);
            command.setYearExpirationUser(expirationUserDate.getYear());
            command.setMonthExpirationUser(new Month(expirationUserDate.getMonthOfYear()).getMonthNum());
            command.setDayExpirationUser(expirationUserDate.getDayOfMonth());

            Integer expirationPasswordMonth = NumberUtils.toInt(
                    ApplicationPropertyManager.getApplicationProperty("user.expiration.password.months"));
            DateTime expirationPasswordDate = (new DateTime()).plusMonths(expirationPasswordMonth);
            command.setYearExpirationPassword(expirationPasswordDate.getYear());
            command.setMonthExpirationPassword(
                    new Month(expirationPasswordDate.getMonthOfYear()).getMonthNum());
            command.setDayExpirationPassword(expirationPasswordDate.getDayOfMonth());

            command.setActive(Boolean.TRUE);
            command.setApproved(Boolean.TRUE);
            command.setLocked(Boolean.FALSE);
        }
    } catch (ApplicationThrowable applicationThrowable) {
        model.put("applicationThrowable", applicationThrowable);
        return new ModelAndView("error/EditUser", model);
    }

    return new ModelAndView("admin/EditUser", model);
}