Example usage for org.joda.time.format DateTimeFormatter parseDateTime

List of usage examples for org.joda.time.format DateTimeFormatter parseDateTime

Introduction

In this page you can find the example usage for org.joda.time.format DateTimeFormatter parseDateTime.

Prototype

public DateTime parseDateTime(String text) 

Source Link

Document

Parses a date-time from the given text, returning a new DateTime.

Usage

From source file:org.fao.geonet.util.JODAISODate.java

License:Open Source License

private static DateTime parseBasicOrFullDateTime(String input1) throws Exception {
    DateTimeFormatter bd = ISODateTimeFormat.basicDate();
    DateTimeFormatter bt = ISODateTimeFormat.basicTime();
    DateTimeFormatter bdt = ISODateTimeFormat.basicDateTime();
    DateTimeFormatter dtp = ISODateTimeFormat.dateTimeParser();
    DateTime idt;/*from w  w w. j a va2s .c  o m*/
    if (input1.length() == 8 && !input1.startsWith("T")) {
        idt = bd.parseDateTime(input1);
    } else if (input1.startsWith("T") && !input1.contains(":")) {
        idt = bt.parseDateTime(input1);
    } else if (input1.contains("T") && !input1.contains(":") && !input1.contains("-")) {
        idt = bdt.parseDateTime(input1);
    } else {
        idt = dtp.parseDateTime(input1);
    }
    return idt;
}

From source file:org.fcrepo.server.utilities.DateUtility.java

License:fedora commons license

/**
 * Attempt to parse the given string of form: yyyy-MM-dd[THH:mm:ss[.SSS][Z]]
 * as a Date.//from   www  . j  a  va 2  s.  co  m
 * 
 * @param dateString
 *            the date string to parse
 * @return a Date representation of the dateString
 * @throws ParseException
 *             if dateString is null, empty or is otherwise unable to be
 *             parsed.
 */
public static Date parseDateStrict(String dateString) throws ParseException {
    try {
        if (dateString == null) {
            throw new ParseException("Argument cannot be null.", 0);
        }

        final int last = dateString.length() - 1;
        if (last == -1) {
            throw new ParseException("Argument cannot be empty.", 0);
        } else if (dateString.charAt(last) == '.') {
            throw new ParseException("dateString ends with invalid character.", last);
        }
        // SimpleDateFormat formatter = new SimpleDateFormat();
        // formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
        final int length = (dateString.charAt(0) != '-') ? last + 1 : last;
        DateTimeFormatter formatter = FORMATTER_MILLISECONDS_T_Z;
        if (dateString.charAt(last) == 'Z') {
            if (length == 11) {
                // formatter.applyPattern("yyyy-MM-dd'Z'");
                formatter = FORMATTER_DATE_Z;
            } else if (length == 20) {
                // formatter.applyPattern("yyyy-MM-dd'T'HH:mm:ss'Z'");
                formatter = FORMATTER_SECONDS_T_Z;
            } else if (length > 21 && length < 24) {
                // right-pad the milliseconds with 0s up to three places
                int endIndex = last - 1;
                int dotIndex = dateString.lastIndexOf('.');
                int padding = 3 - (endIndex - dotIndex);
                if (padding > 0) {
                    StringBuilder sb = new StringBuilder(24);
                    sb.append(dateString.subSequence(0, last));
                    switch (padding) {
                    case 3:
                        sb.append('0');
                    case 2:
                        sb.append('0');
                    case 1:
                        sb.append('0');
                    }
                    sb.append('Z');
                    dateString = sb.toString();
                }
                // formatter.applyPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
                formatter = FORMATTER_MILLISECONDS_T_Z;
            } else if (length == 24) {
                // formatter.applyPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
                formatter = FORMATTER_MILLISECONDS_T_Z;
            }
        } else {
            if (length == 10) {
                // formatter.applyPattern("yyyy-MM-dd");
                formatter = FORMATTER_DATE;
            } else if (length == 19) {
                // formatter.applyPattern("yyyy-MM-dd'T'HH:mm:ss");
                formatter = FORMATTER_SECONDS_T;
            } else if (length > 20 && length < 23) {
                // right-pad millis with 0s
                int endIndex = dateString.length() - 1;
                int dotIndex = dateString.lastIndexOf('.');
                int padding = 3 - (endIndex - dotIndex);
                if (padding > 0) {
                    StringBuilder sb = new StringBuilder(23);
                    sb.append(dateString);
                    switch (padding) {
                    case 3:
                        sb.append('0');
                    case 2:
                        sb.append('0');
                    case 1:
                        sb.append('0');
                    }
                    dateString = sb.toString();
                }
                // formatter.applyPattern("yyyy-MM-dd'T'HH:mm:ss.SSS");
                formatter = FORMATTER_MILLISECONDS_T;
            } else if (length == 23) {
                // formatter.applyPattern("yyyy-MM-dd'T'HH:mm:ss.SSS");
                formatter = FORMATTER_MILLISECONDS_T;
            } else if (dateString.endsWith("GMT") || dateString.endsWith("UTC")) {
                // formatter.applyPattern("EEE, dd MMMM yyyyy HH:mm:ss z");
                // this has to be done by hand since Joda time can't parse
                // the timezone
                // see
                // http://joda-time.sourceforge.net/apidocs/org/joda/time/format/DateTimeFormat.html
                dateString = dateString.substring(0, last - 3);
                formatter = FORMATTER_TIMEZONE;
            }
        }
        DateTimeZone.setDefault(DateTimeZone.UTC);
        DateTime dt = formatter.parseDateTime(dateString);
        return dt.toDate();
    } catch (IllegalArgumentException e) {
        throw new ParseException(e.getLocalizedMessage(), 0);
    }
}

From source file:org.fenixedu.academic.thesis.ui.controller.ConfigurationController.java

License:Open Source License

@Atomic(mode = TxMode.WRITE)
private void edit(ConfigurationBean configurationBean) throws OverlappingIntervalsException {

    ThesisProposalsConfiguration thesisProposalsConfiguration = FenixFramework
            .getDomainObject(configurationBean.getExternalId());

    DateTimeFormatter formatter = ISODateTimeFormat.dateTime();

    DateTime proposalPeriodStartDT = formatter.parseDateTime(configurationBean.getProposalPeriodStart());
    DateTime proposalPeriodEndDT = formatter.parseDateTime(configurationBean.getProposalPeriodEnd());
    DateTime candidacyPeriodStartDT = formatter.parseDateTime(configurationBean.getCandidacyPeriodStart());
    DateTime candidacyPeriodEndDT = formatter.parseDateTime(configurationBean.getCandidacyPeriodEnd());

    Interval proposalPeriod = new Interval(proposalPeriodStartDT, proposalPeriodEndDT);
    Interval candidacyPeriod = new Interval(candidacyPeriodStartDT, candidacyPeriodEndDT);

    for (ThesisProposalsConfiguration config : thesisProposalsConfiguration.getExecutionDegree()
            .getThesisProposalsConfigurationSet()) {
        if (!config.equals(thesisProposalsConfiguration) && (config.getProposalPeriod().overlaps(proposalPeriod)
                || config.getCandidacyPeriod().overlaps(candidacyPeriod)
                || config.getProposalPeriod().overlaps(candidacyPeriod)
                || config.getCandidacyPeriod().overlaps(proposalPeriod))) {
            throw new OverlappingIntervalsException();
        }/*  w w w . j  a  va2s .  c  o m*/
    }

    Set<ThesisProposalsConfiguration> sharedConfigs = thesisProposalsConfiguration.getThesisProposalSet()
            .stream().flatMap(proposal -> proposal.getThesisConfigurationSet().stream())
            .collect(Collectors.toSet());
    sharedConfigs.add(thesisProposalsConfiguration);

    sharedConfigs.forEach(config -> {
        config.setProposalPeriod(proposalPeriod);
        config.setCandidacyPeriod(candidacyPeriod);

        config.setMaxThesisCandidaciesByStudent(configurationBean.getMaxThesisCandidaciesByStudent());
        config.setMaxThesisProposalsByUser(configurationBean.getMaxThesisProposalsByUser());

        config.setMinECTS1stCycle(configurationBean.getMinECTS1stCycle());
        config.setMinECTS2ndCycle(configurationBean.getMinECTS2ndCycle());
    });

}

From source file:org.fenixedu.cms.api.json.PostAdapter.java

License:Open Source License

public static DateTime parseDate(String date) {
    DateTimeFormatter formatter = ISODateTimeFormat.dateHourMinute();
    DateTime dateTime = formatter.parseDateTime(date);
    return dateTime;
}

From source file:org.fenixedu.parking.ui.Action.ManageParkingCardsDA.java

License:Open Source License

private ParkingCardSearchBean getSearchParameters(HttpServletRequest request) {
    ParkingCardSearchBean parkingCardSearchBean = new ParkingCardSearchBean();
    String parkingCardUserState = request.getParameter("parkingCardUserState");
    if (!StringUtils.isEmpty(parkingCardUserState)) {
        parkingCardSearchBean.setParkingCardUserState(ParkingCardUserState.valueOf(parkingCardUserState));
    }//  ww w . ja va2 s . c  o  m
    String parkingGroupID = request.getParameter("parkingGroupID");
    if (!StringUtils.isEmpty(parkingGroupID)) {
        parkingCardSearchBean.setParkingGroup(FenixFramework.<ParkingGroup>getDomainObject(parkingGroupID));
    }
    String actualEndDate = request.getParameter("actualEndDate");
    if (!StringUtils.isEmpty(actualEndDate)) {
        DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyy-MM-dd");
        parkingCardSearchBean.setActualEndDate(dtf.parseDateTime(actualEndDate).toYearMonthDay());
    }
    String parkingCardSearchPeriod = request.getParameter("parkingCardSearchPeriod");
    if (!StringUtils.isEmpty(parkingCardSearchPeriod)) {
        parkingCardSearchBean
                .setParkingCardSearchPeriod(ParkingCardSearchPeriod.valueOf(parkingCardSearchPeriod));
    }
    return parkingCardSearchBean;
}

From source file:org.fenixedu.ulisboa.specifications.domain.student.access.importation.DgesStudentImportationProcess.java

License:Open Source License

protected void fillMainInformation(DegreeCandidateDTO degreeCandidateDTO, String line) {
    String[] fields = splitLine(line, MAIN_INFORMATION_LINE_FIELD_SPEC);
    degreeCandidateDTO.setDegreeCode(fields[1].trim());
    degreeCandidateDTO.setDocumentIdNumber(fields[2].trim());
    degreeCandidateDTO.setGender(parseGender(fields[4].trim()));

    DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyyMMdd");
    DateTime date = formatter.parseDateTime(fields[5].trim());
    degreeCandidateDTO.setDateOfBirth(date.toYearMonthDay());

    degreeCandidateDTO.setContigent(fields[6].trim());
    degreeCandidateDTO.setPlacingOption(Integer.valueOf(fields[7].trim()));
    degreeCandidateDTO.setIngression(getIngression(degreeCandidateDTO.getContigent()));
    BigDecimal entryGrade = new BigDecimal(fields[10].trim().replace(",", "."));
    degreeCandidateDTO.setEntryGrade(entryGrade.setScale(1, RoundingMode.HALF_EVEN).doubleValue());
    BigDecimal highSchoolEntryGrade = entryGrade.setScale(2, RoundingMode.HALF_EVEN);
    highSchoolEntryGrade = highSchoolEntryGrade.divide(new BigDecimal(10), RoundingMode.HALF_EVEN);
    degreeCandidateDTO/*from   w ww  .  ja  va2s .  c  o  m*/
            .setHighSchoolFinalGrade(highSchoolEntryGrade.setScale(0, RoundingMode.HALF_EVEN).toString());
    degreeCandidateDTO.setName(fields[11].trim());
    Country nationality = Country.readByTwoLetterCode(fields[15].trim());
    if (nationality == null) {
        throw new RuntimeException("Cannot import student with unknown nationality: " + fields[15].trim());
    }
    degreeCandidateDTO.setNationality(nationality);
}

From source file:org.finra.datagenerator.engine.scxml.tags.boundary.BoundaryDate.java

License:Apache License

/**
 * Takes a date, and retrieves the next business day
 *
 * @param dateString the date/*from  w  w  w  .  j a  v  a 2s.  co m*/
 * @param onlyBusinessDays only business days
 * @return a string containing the next business day
 */
public String getNextDay(String dateString, boolean onlyBusinessDays) {
    DateTimeFormatter parser = ISODateTimeFormat.date();
    DateTime date = parser.parseDateTime(dateString).plusDays(1);
    Calendar cal = Calendar.getInstance();
    cal.setTime(date.toDate());

    if (onlyBusinessDays) {
        if (cal.get(Calendar.DAY_OF_WEEK) == 1 || cal.get(Calendar.DAY_OF_WEEK) == 7
                || isHoliday(date.toString().substring(0, 10))) {
            return getNextDay(date.toString().substring(0, 10), true);
        } else {
            return parser.print(date);
        }
    } else {
        return parser.print(date);
    }
}

From source file:org.finra.datagenerator.engine.scxml.tags.boundary.BoundaryDate.java

License:Apache License

/**
 * Takes a date, and returns the previous business day
 *
 * @param dateString the date//from www.  jav  a 2  s. c  o  m
 * @param onlyBusinessDays only business days
 * @return the previous business day
 */
public String getPreviousDay(String dateString, boolean onlyBusinessDays) {
    DateTimeFormatter parser = ISODateTimeFormat.date();
    DateTime date = parser.parseDateTime(dateString).minusDays(1);
    Calendar cal = Calendar.getInstance();
    cal.setTime(date.toDate());

    if (onlyBusinessDays) {
        if (cal.get(Calendar.DAY_OF_WEEK) == 1 || cal.get(Calendar.DAY_OF_WEEK) == 7
                || isHoliday(date.toString().substring(0, 10))) {
            return getPreviousDay(date.toString().substring(0, 10), true);
        } else {
            return parser.print(date);
        }
    } else {
        return parser.print(date);
    }
}

From source file:org.finra.datagenerator.engine.scxml.tags.boundary.BoundaryDate.java

License:Apache License

/**
 * @param isNullable isNullable//from   w  w w  . j a va2  s .  co  m
 * @param earliest   lower boundary date
 * @param latest     upper boundary date
 * @param onlyBusinessDays only business days
 * @return a list of boundary dates
 */
public List<String> positiveCase(boolean isNullable, String earliest, String latest, boolean onlyBusinessDays) {
    List<String> values = new LinkedList<>();

    if (earliest.equalsIgnoreCase(latest)) {
        values.add(earliest);
        if (isNullable) {
            values.add("");
        }
        return values;
    }

    DateTimeFormatter parser = ISODateTimeFormat.date();
    DateTime earlyDate = parser.parseDateTime(earliest);
    DateTime lateDate = parser.parseDateTime(latest);

    String earlyDay = parser.print(earlyDate);
    String nextDay = getNextDay(earlyDate.toString().substring(0, 10), onlyBusinessDays);
    String prevDay = getPreviousDay(lateDate.toString().substring(0, 10), onlyBusinessDays);
    String lateDay = parser.print(lateDate);

    values.add(earlyDay);
    values.add(nextDay);
    values.add(prevDay);
    values.add(lateDay);

    if (isNullable) {
        values.add("");
    }
    return values;
}

From source file:org.finra.datagenerator.engine.scxml.tags.boundary.BoundaryDate.java

License:Apache License

/**
 * @param isNullable isNullable/* ww  w  .ja  v  a 2 s  .c  o  m*/
 * @param earliest   lower boundary date
 * @param latest     upper boundary date
 * @return a list of boundary dates
 */
public List<String> negativeCase(boolean isNullable, String earliest, String latest) {
    List<String> values = new LinkedList<>();

    DateTimeFormatter parser = ISODateTimeFormat.date();
    DateTime earlyDate = parser.parseDateTime(earliest);
    DateTime lateDate = parser.parseDateTime(latest);

    String prevDay = parser.print(earlyDate.minusDays(1));
    String nextDay = parser.print(lateDate.plusDays(1));

    values.add(prevDay);
    values.add(nextDay);
    values.add(nextDay.substring(5, 7) + "-" + nextDay.substring(8, 10) + "-" + nextDay.substring(0, 4));
    values.add(getRandomHoliday(earliest, latest));

    if (!isNullable) {
        values.add("");
    }
    return values;
}