Example usage for org.joda.time LocalDate parse

List of usage examples for org.joda.time LocalDate parse

Introduction

In this page you can find the example usage for org.joda.time LocalDate parse.

Prototype

public static LocalDate parse(String str, DateTimeFormatter formatter) 

Source Link

Document

Parses a LocalDate from the specified string using a formatter.

Usage

From source file:com.sonicle.webtop.core.sdk.BaseSettings.java

License:Open Source License

public LocalDate getDate(String key, LocalDate defaultValue, String pattern) {
    DateTimeFormatter dtf = DateTimeFormat.forPattern(pattern).withZone(DateTimeZone.getDefault());
    String value = getString(key, null);
    return (value == null) ? defaultValue : LocalDate.parse(value, dtf);
}

From source file:com.the.todo.parser.DateAndTimeParser.java

License:MIT License

public static boolean checkValidDates(String input) {
    boolean isValid = true;
    Pattern pattern = Pattern.compile("(?:\\d*)?\\d+[/-](?:\\d*)?\\d+[/-](?:\\d*)?\\d+");
    Matcher matcher = pattern.matcher(input);

    while (matcher.find()) {
        String matchedDate = matcher.group();
        try {//  ww w .  j  a  v  a2  s . co  m
            LocalDate.parse(matchedDate, DATE_TIME_FORMATTER);
        } catch (Exception e) {
            isValid = false;
            break;
        }
    }

    return isValid;
}

From source file:com.the.todo.parser.DateAndTimeParser.java

License:MIT License

public static String changeDateStringsFormat(String input) {
    String formattedInput = input;
    Pattern pattern = Pattern.compile(
            "(?:(?:31(\\/|-|\\.)(?:0?[13578]|1[02]))\\1|(?:(?:29|30)(\\/|-|\\.)(?:0?[1,3-9]|1[0-2])\\2))(?:(?:1[6-9]|[2-9]\\d)?\\d{2})|\\b(?:29(\\/|-|\\.)0?2\\3(?:(?:(?:1[6-9]|[2-9]\\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))|\\b(?:0?[1-9]|1\\d|2[0-8])(\\/|-|\\.)(?:(?:0?[1-9])|(?:1[0-2]))\\4(?:(?:1[6-9]|[2-9]\\d)?\\d{2})");
    Matcher matcher = pattern.matcher(input);

    while (matcher.find()) {
        String matchedDate = matcher.group();
        LocalDate date = LocalDate.parse(matchedDate, DAY_MONTH_YEAR_SLASH);
        formattedInput = formattedInput.replace(matchedDate, date.toString(YEAR_MONTH_DAY_SLASH));
        System.out.println(formattedInput);
    }/*from   w ww .jav a  2 s  .c  o  m*/

    return formattedInput;
}

From source file:com.thinkbiganalytics.policy.standardization.DateTimeStandardizer.java

License:Apache License

@Override
public String convertValue(String value) {
    if (valid) {/*ww w.  ja v a 2 s. com*/
        try {
            if (inputFormatter == null) {
                if (isInputUnixTimestamp(value)) {
                    //unix timestamp are in seconds
                    long lValue = Long.parseLong(value);
                    lValue *= 1000;
                    return outputFormatter.print(lValue);
                } else {
                    long lValue = Long.parseLong(value);
                    return outputFormatter.print(lValue);
                }
            }

            DateTime dt = inputFormatter.parseDateTime(value);

            return outputFormatter.print(dt);
        } catch (IllegalInstantException e) {
            if ((inputTimezone == null && !JodaUtils.formatContainsTime(this.inputDateFormat))
                    && outputFormat == OutputFormats.DATE_ONLY) {
                // in the case where user is not matching time in the formatString, has not specified the
                //    input time zone and the output format is DATE_ONLY, it is safe to retry with
                //    a "timezone-less" date parsing to avoid any time zone offset transition problems
                //    on the input date.  output date
                DateTime dt = LocalDate.parse(value, inputFormatter).toDateTimeAtStartOfDay();
                return outputFormatter.print(dt);
            } else {
                // otherwise...  we can't be sure how an incoming date in time
                //    zone offset transition should be handled.  It is best to skip the conversion
                //    and hope the feed has a validator that would catch the row as invalid, so
                //    the problem can be addressed at the source.
                throw e;
            }
        } catch (IllegalArgumentException e) {
            log.debug("Failed to convert string [{}] to date pattern [{}], value, inputDateFormat");
        }
    }
    return value;
}

From source file:com.thinkbiganalytics.policy.validation.DateValidator.java

License:Apache License

/**
 * Parses the string date and returns the
 *///from   w  w  w .  ja va 2  s .  com
public DateTime parseDate(String value) {
    int cnt = value.length();
    if (cnt == LENGTH) {
        return LocalDate.parse(value, DATE).toDateTimeAtStartOfDay();
    } else {
        throw new IllegalArgumentException("Expecting yyyy-MM-dd");
    }
}

From source file:courtscheduler.domain.DateConstraint.java

License:Apache License

public Integer findDate(String date) {
    LocalDate ldate = LocalDate.parse(date, dateFormat);
    return findDate(ldate);
}

From source file:courtscheduler.domain.DateConstraint.java

License:Apache License

public int[] findDateRange(String startDate, String endDate) {
    LocalDate sdate = LocalDate.parse(startDate, dateFormat);
    LocalDate edate = LocalDate.parse(endDate, dateFormat);
    return this.findDateRange(sdate, edate);
}

From source file:courtscheduler.persistence.CourtScheduleInfo.java

License:Apache License

public int configure() {
    raw_lines = slurpConfigFile(this.filepath);
    if (raw_lines.size() == 0) {
        error(true,/*w  w w  .  jav a 2s.  co  m*/
                "Could not read anything from the configuration file." + EOL
                        + "Expected the configuration file to be found at: "
                        + FileSystems.getDefault().getPath(filepath).toAbsolutePath());
    }
    String[] scheduleDescription = new String[0];
    for (String line : raw_lines) {
        if (line.startsWith(";", 0) || line.trim().length() == 0) {
            // this line is a comment or empty line
            continue;
        }
        String[] lineComponents = line.split("=");
        if (lineComponents.length < 2) {
            System.out.println("could not interpret line: " + line);
            continue;
        }

        String key = lineComponents[0].trim();
        String value = lineComponents[1].trim();

        if (key.equals("conference_start")) {
            this.conferenceStartDate = parseDateString(value);
        } else if (key.equals("conference_end")) {
            this.conferenceEndDate = parseDateString(value);
        } else if (key.equals("court_count")) {
            this.numberOfCourts = Integer.parseInt(value);
        } else if (key.equals("timeslots_count")) {
            this.numberOfTimeSlotsPerDay = Integer.parseInt(value);
        } else if (key.equals("timeslot_duration_minutes")) {
            this.timeslotDurationInMinutes = Integer.parseInt(value);
        } else if (key.equals("timeslots_start")) {
            this.timeslotMidnightOffsetInMinutes = timeStringToMinutes(value);
        } else if (key.startsWith("conference")) {
            this.parseConferenceDays(value);
        } else if (key.startsWith("holiday")) {
            if (!value.contains("-")) {
                // one date
                holidays.add(LocalDate.parse(value, DateConstraint.dateFormat));
            } else {
                // date range
                LocalDate start = LocalDate.parse(value.substring(0, value.indexOf("-")),
                        DateConstraint.dateFormat);
                LocalDate end = LocalDate.parse(value.substring(value.indexOf("-") + 1),
                        DateConstraint.dateFormat);
                LocalDate next = start;
                while (next.isBefore(end)) {
                    holidays.add(next);
                    next = next.plusDays(1);
                }
                holidays.add(end);
            }
        } else if (key.startsWith("schedule_description")) {
            scheduleDescription = value.split(", ");
        }

        else if (key.startsWith("input_file")) {
            inputFileLocation = value;
        }

        else if (key.startsWith("output_folder")) {
            outputFolderLocation = value;
        }
    }
    DateConstraint.setStandardDates(this.createStandardSchedule(scheduleDescription));
    return 0;
}

From source file:de.appsolve.padelcampus.admin.controller.bookings.AdminBookingsReservationsController.java

@Override
public ModelAndView showIndex(HttpServletRequest request, Pageable pageable, String search) {
    String startDateStr = request.getParameter("startDate");
    String endDateStr = request.getParameter("endDate");
    LocalDate startDate = sessionUtil.getBookingListStartDate(request);
    if (startDate == null) {
        startDate = new LocalDate();
    }//from  w w  w .ja va  2s  .  c o  m
    if (!StringUtils.isEmpty(startDateStr)) {
        try {
            startDate = LocalDate.parse(startDateStr, DATE_HUMAN_READABLE);
        } catch (IllegalArgumentException e) {
            //ignore
        }
    }
    sessionUtil.setBookingListStartDate(request, startDate);
    LocalDate endDate = new LocalDate(startDate);
    if (!StringUtils.isEmpty(endDateStr)) {
        try {
            endDate = LocalDate.parse(endDateStr, DATE_HUMAN_READABLE);
        } catch (IllegalArgumentException e) {
            //ignore
        }
    }
    if (endDate.isBefore(startDate)) {
        endDate = new LocalDate(startDate);
    }

    DateRange dateRange = new DateRange();
    dateRange.setStartDate(startDate);
    dateRange.setEndDate(endDate);
    return getIndexView(dateRange);
}

From source file:de.iteratec.iteraplan.presentation.dialog.History.HistoryController.java

License:Open Source License

/**
 * URL Handler method that returns an HTML view of the history of one building block, narrowed down by provided criteria
 * @param bbId Building Block ID//from   w w w .  j a v  a2  s  .  c  o m
 * @param bbType Building Block type code, which can be decoded by {@link TypeOfBuildingBlock#fromInitialCapString(String)}
 * @param page The number of the page to return, depending on {@code pageSize}. Zero-based. May be {@code null}, in which case the default value 0 is used.
 * @param pageSize The number of history events on the returned page. -1 is interpreted as "everything". May be {@code null}, in which case the default value -1 is used.
 * @param dateFromStr The start date of the time range to filter history events for. This is expected to be in ISO date format (pattern yyyy-MM-dd)!
 * @param dateToStr The end date (inclusive) of the time range to filter history events for. This is expected to be in ISO date format (pattern yyyy-MM-dd)!
 */
@SuppressWarnings("boxing")
@RequestMapping
public ModelAndView localHistory(@RequestParam(value = "id", required = true) String bbId,
        @RequestParam(value = "buildingBlockType", required = true) String bbType,
        @RequestParam(value = "page", required = false) String page,
        @RequestParam(value = "pageSize", required = false) String pageSize,
        @RequestParam(value = "dateFrom", required = false) String dateFromStr,
        @RequestParam(value = "dateTo", required = false) String dateToStr) {

    ModelAndView modelAndView = new ModelAndView("history/local");

    // Check if user may see history, and note so JSP can show a nice error. If not, return
    Boolean hasPermission = Boolean.valueOf(UserContext.getCurrentPerms().getUserHasFuncPermViewHistory());
    modelAndView.addObject("isHasViewHistoryPermission", hasPermission);
    if (!hasPermission.booleanValue()) {
        return modelAndView;
    }

    int id = parseInt(bbId, -1);

    // Default to showing page 0 (first page), if unspecified
    int curPage = parseInt(page, 0);
    // current page must not be negative
    curPage = Math.max(curPage, 0);

    // Default -1 means infinite results Per Page
    int pageSizeInt = parseInt(pageSize, -1);
    // make sure it's not 0, /0 error later; and make all values < -1 turn into -1
    if (pageSizeInt <= 0) {
        pageSizeInt = -1;
    }

    DateTimeFormatter isoDateFormatter = ISODateTimeFormat.date();
    DateTime dateFrom = null;
    DateTime dateTo = null;
    if (StringUtils.isNotEmpty(dateFromStr)) {
        try {
            LocalDate date = LocalDate.parse(dateFromStr, isoDateFormatter);
            dateFrom = date.toDateTimeAtStartOfDay();
        } catch (IllegalArgumentException ex) {
            // invalid date format, ignore
        }
    }

    if (StringUtils.isNotEmpty(dateToStr)) {
        try {
            // assumption: we parsed from a date with no time which gave us the beginning of that day, but
            // we want to include the whole day, so add 1 day
            LocalDate date = LocalDate.parse(dateToStr, isoDateFormatter).plusDays(1);
            dateTo = date.toDateTimeAtStartOfDay();
        } catch (IllegalArgumentException ex) {
            // invalid date format, ignore
        }
    }

    HistoryResultsPage resultsPage;
    try {
        resultsPage = historyService.getLocalHistoryPage(getClassFromTypeString(bbType), id, curPage,
                pageSizeInt, dateFrom, dateTo);
    } catch (Exception e) {
        throw new IteraplanTechnicalException(IteraplanErrorMessages.HISTORY_RETRIEVAL_GENERAL_ERROR, e);
    }
    assert resultsPage != null;

    modelAndView.addObject("resultsPage", resultsPage);
    modelAndView.addObject("isHistoryEnabled", Boolean.valueOf(historyService.isHistoryEnabled()));

    return modelAndView;
}