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.opentestsystem.delivery.testreg.eligibility.EligibilityEvaluatorCache.java

License:Open Source License

@SuppressWarnings("unchecked")
private <T> T convertTo(final String value, final Class<T> clazz) {

    try {/*from   w  w w . j a va 2  s  .c  om*/
        if (String.class.isAssignableFrom(clazz)) {
            return (T) value;
        } else if (Number.class.isAssignableFrom(clazz)) {
            return clazz.getConstructor(String.class).newInstance(value);
        } else if (DateTime.class.isAssignableFrom(clazz)) {
            DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
            DateTime dateTime = formatter.parseDateTime(value);
            return (T) dateTime;
        } else if (Enum.class.isAssignableFrom(clazz)) {
            Method getEnum = null;
            try {
                getEnum = clazz.getDeclaredMethod("getEnumByValue", String.class);
            } catch (final NoSuchMethodException me) {
                getEnum = clazz.getMethod("valueOf", String.class);
            }
            return (T) getEnum.invoke(null, value);
        } else {
            LOGGER.error("Failure to convert value \"" + value + "\" into class type " + clazz.toString());
            throw new EligibilityException("eligibility.value.convert.error",
                    new String[] { value, clazz.toString() });
        }
    } catch (InstantiationException | IllegalAccessException | IllegalArgumentException
            | InvocationTargetException | NoSuchMethodException | SecurityException e) {
        LOGGER.error("Failure to convert value \"" + value + "\" into class type " + clazz.toString(), e);
        throw new EligibilityException("eligibility.value.convert.error",
                new String[] { value, clazz.toString() }, e);
    }
}

From source file:org.opentripplanner.updater.stoptime.KV8Update.java

License:Open Source License

private static long kv8Timestamp(HashMap<String, String> row) {
    String timestamp = row.get("LastUpdateTimeStamp");
    DateTimeFormatter parser = ISODateTimeFormat.dateTimeNoMillis();
    DateTime dt = parser.parseDateTime(timestamp);
    return dt.getMillis();
}

From source file:org.oscarehr.olis.OLISPreferencesAction.java

License:Open Source License

@Override
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    DateTimeFormatter input = DateTimeFormat.forPattern("YYYY-MM-dd HH:mm:ss Z");
    DateTimeFormatter output = DateTimeFormat.forPattern("YYYYMMddHHmmssZ");
    DateTime date;//  w ww .  j  a  va  2 s .  co m
    String startTime = oscar.Misc.getStr(request.getParameter("startTime"), "").trim();
    if (!startTime.equals("")) {
        date = input.parseDateTime(startTime);
        startTime = date.toString(output);
    }
    String endTime = oscar.Misc.getStr(request.getParameter("endTime"), "").trim();
    if (!endTime.equals("")) {
        date = input.parseDateTime(endTime);
        endTime = date.toString(output);
    }

    Integer pollFrequency = oscar.Misc.getInt(request.getParameter("pollFrequency"), 30);
    String filterPatients = request.getParameter("filter_patients");
    OLISSystemPreferencesDao olisPrefDao = (OLISSystemPreferencesDao) SpringUtils
            .getBean("OLISSystemPreferencesDao");
    OLISSystemPreferences olisPrefs = olisPrefDao.getPreferences();

    try {
        olisPrefs.setStartTime(startTime);
        olisPrefs.setEndTime(endTime);
        olisPrefs.setFilterPatients((filterPatients != null) ? true : false);
        boolean restartTimer = olisPrefs.getPollFrequency() != pollFrequency;
        olisPrefs.setPollFrequency(pollFrequency);
        olisPrefDao.save(olisPrefs);
        request.setAttribute("success", true);

        if (restartTimer) {
            ScheduledTimerTask task = (ScheduledTimerTask) SpringUtils.getBean("olisScheduledPullTask");
            TimerTask tt = task.getTimerTask();
            Thread t = new Thread(tt);
            t.start();
        }

    } catch (Exception e) {
        MiscUtils.getLogger().error("Changing Preferences failed", e);
        request.setAttribute("success", false);
    }

    return mapping.findForward("success");

}

From source file:org.osframework.util.DateUtil.java

License:Apache License

/**
 * Parse the date represented by the specified string. This method handles
 * dates in these formats://from  w  w w .  ja  va 2s.  com
 * <ul>
 *    <li>yyyyMMdd</li>
 *    <li>yyyy-MM-dd</li>
 *    <li>yyyy/MM/dd</li>
 *    <li>MM/dd/yyyy</li>
 * </ul>
 * 
 * @param s date string to be parsed
 * @return represented date
 * @throws IllegalArgumentException if specified string is empty
 */
public static Date parseDate(String s) {
    if (StringUtils.isBlank(s)) {
        throw new IllegalArgumentException("Invalid date string: " + s);
    }
    String trimmed = s.trim();
    Date d = null;
    if (isNumber(trimmed)) {
        d = FORMAT_DATE_ISO8601_INT.parseDateTime(trimmed).toDate();
    } else {
        int idx = findArrayIndex(trimmed);
        if (-1 == idx) {
            throw new IllegalArgumentException("Invalid date string: " + s);
        }
        DateTimeFormatter dtf = FORMAT_ARRAY[idx];
        d = dtf.parseDateTime(trimmed).toDate();
    }
    return d;
}

From source file:org.owasp.webscarab.plugin.openid.PAPEResponse.java

License:Open Source License

public void setAuthenticationTime(String authenticationTimeStr) {
    DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyy-MM-dd'T'HH:mm:ss'Z'");
    DateTime dateTime = dateTimeFormatter.parseDateTime(authenticationTimeStr);
    this.authenticationTime = dateTime.withZoneRetainFields(DateTimeZone.UTC).toDate();
}

From source file:org.patientview.monitoring.ImportMonitor.java

License:Open Source License

private static Date parseDate(String maybeDate, String format) {
    Date date = null;//ww w  .j  ava2 s  .co m

    try {
        DateTimeFormatter fmt = DateTimeFormat.forPattern(format);
        DateTime dateTime = fmt.parseDateTime(maybeDate);
        date = dateTime.toDate();
    } catch (Exception e) {
        LOGGER.error("Invalid date: {}", maybeDate, e);
    }

    return date;
}

From source file:org.patientview.patientview.utils.TimestampUtils.java

License:Open Source License

public static Calendar createTimestamp(String dateTimeString) {
    Calendar cal = new GregorianCalendar();
    DateTimeFormatter formatter = null;

    try {//from   ww  w . j av a2 s .  co m
        if (dateTimeString.contains("-")) {
            if (dateTimeString.indexOf("-") == 2) {
                formatter = DateTimeFormat.forPattern(DAY_FORMAT_DASH);
            } else if (dateTimeString.indexOf("-") == YEAR_FIRST_DASH_POS
                    && dateTimeString.length() == DATE_WITH_SECONDS_LENGTH
                    && dateTimeString.indexOf("T") == ISO_DATE_T_POS) {
                formatter = DateTimeFormat.forPattern(DAY_FORMAT_DASH_BACKWARDS_WITH_T_HOUR_MINUTE_AND_SECOND);
            } else if (dateTimeString.indexOf("-") == YEAR_FIRST_DASH_POS
                    && dateTimeString.length() == DATE_WITH_SECONDS_LENGTH
                    && dateTimeString.indexOf(" ") == NORMAL_DATE_SPACE_POS) {
                formatter = DateTimeFormat.forPattern(DAY_FORMAT_DASH_BACKWARDS_WITH_HOUR_MINUTE_AND_SECOND);
            } else if (dateTimeString.indexOf("-") == YEAR_FIRST_DASH_POS
                    && dateTimeString.length() == DATE_WITH_MINUTES_LENGTH) {
                formatter = DateTimeFormat.forPattern(DAY_FORMAT_DASH_BACKWARDS_WITH_HOUR_AND_MINUTE);
            } else if (dateTimeString.indexOf("-") == YEAR_FIRST_DASH_POS
                    && dateTimeString.length() == DATE_ONLY_LENGTH) {
                formatter = DateTimeFormat.forPattern(DAY_FORMAT_DASH_BACKWARDS);
            }

            DateTime dateTime;
            if (formatter == null) {
                dateTime = new DateTime(dateTimeString);
            } else {
                dateTime = formatter.parseDateTime(dateTimeString);
            }

            cal.setTime(dateTime.toDate());
        } else {
            AtomicReference<Date> date = new AtomicReference<Date>();

            if (dateTimeString.indexOf("/") == 2) {
                date.set(DAY_FORMAT_SLASH.parse(dateTimeString));
                cal.setTime(date.get());
            } else {
                date.set(DAY_FORMAT_SLASH_BACKWARDS.parse(dateTimeString));
                cal.setTime(date.get());
            }
        }
    } catch (Exception e) {
        LOGGER.error("Can not parse date {}", dateTimeString, e.getMessage());

        cal = null;
    }

    return cal;
}

From source file:org.pentaho.metadata.query.model.util.DataTypeDetector.java

License:Open Source License

/**
 * Class used to detect and modify the column type based on incoming string values. The DataTypeDetector is currently
 * able to detect the following column types:
 * <ul>/*from w ww .j  a  va  2 s  .co m*/
 * <li>Strings (default if no other type is found)</li>
 * <li>Booleans</li>
 * <li>Integers</li>
 * <li>Doubles</li>
 * <li>Date</li>
 * <li>Time</li>
 * </ul>
 * And it will also detect if the column is nullable, ie. if null occurs in the values.
 */
public static DataType getDataType(String valueAsString) {
    DataType returnType = null;
    boolean _booleanPossible = true;
    boolean _integerPossible = true;
    boolean _doublePossible = true;
    boolean _datePossible = true;
    boolean _timePossible = true;
    boolean _nullPossible = false;

    if (valueAsString == null) {
        _nullPossible = true;
    } else {
        if (_booleanPossible) {
            try {
                BooleanComparator.parseBoolean(valueAsString);
            } catch (IllegalArgumentException e) {
                _booleanPossible = false;
            }
        }
        if (_doublePossible) {
            try {
                Double.parseDouble(valueAsString);
            } catch (NumberFormatException e) {
                _doublePossible = false;
                _integerPossible = false;
            }
            // If integer is possible, double will always also be possible,
            // but not nescesarily the other way around
            if (_integerPossible) {
                try {
                    Integer.parseInt(valueAsString);
                } catch (NumberFormatException e) {
                    _integerPossible = false;
                }
            }
        }
        if (_datePossible) {
            DateTimeFormatter fmt = null;
            for (String mask : COMMON_DATE_FORMATS) {
                try {
                    fmt = DateTimeFormat.forPattern(mask);
                    fmt.parseDateTime(valueAsString);
                    _datePossible = true;
                    break;
                } catch (IllegalArgumentException e) {
                    _datePossible = false;
                }
            }
        }
        if (_timePossible) {
            try {
                new LocalTime(valueAsString);
            } catch (IllegalArgumentException e) {
                _timePossible = false;
            }
        }
    }

    if (_booleanPossible) {
        returnType = DataType.BOOLEAN;
    } else if (_integerPossible) {
        returnType = DataType.NUMERIC;
    } else if (_doublePossible) {
        // TODO We need to find a way of passing double in the model as a data type. For now all doubles will be set to
        // NUMERIC
        // returnType = DataType.DOUBLE;
        returnType = DataType.NUMERIC;
    } else if (_datePossible) {
        returnType = DataType.DATE;
    } else if (_timePossible) {
        // TODO We need to find a way of passing TIME in the model as a data type. For now all TIME will be set to DATE
        // returnType = DataType.TIME;
        returnType = DataType.DATE;
    } else {
        returnType = DataType.STRING;
    }
    return returnType;
}

From source file:org.phenotips.data.internal.controller.Biospecimen.java

License:Open Source License

/**
 * Populates this Biospecimen object with the contents of the given JSONObject.
 * @param jsonObject the JSONObject to parse (can be null)
 * @throws IllegalArgumentException if incoming object is invalid
 * @throws UnsupportedOperationException if any field parsing fails
 *//*from w  w w  . j  av a  2s .  com*/
public Biospecimen(JSONObject jsonObject) throws IllegalArgumentException, UnsupportedOperationException {
    if (jsonObject == null) {
        return;
    }

    DateTimeFormatter formatter = ISODateTimeFormat.date();

    for (String property : Biospecimen.PROPERTIES) {
        String value = jsonObject.optString(property);

        if (StringUtils.isBlank(value)) {
            continue;
        }

        switch (property) {
        case Biospecimen.TYPE_PROPERTY_NAME:
            this.setType(value);
            break;
        case Biospecimen.DATE_COLLECTED_PROPERTY_NAME:
            this.setDateCollected(formatter.parseDateTime(value));
            break;
        case Biospecimen.DATE_RECEIVED_PROPERTY_NAME:
            this.setDateReceived(formatter.parseDateTime(value));
            break;
        default:
            break;
        }
    }
}

From source file:org.powertac.common.Competition.java

License:Apache License

/**
 * Fluent setter for simulation base time that takes a String, interpreted
 * as a standard DateTimeFormat as yyyy-MM-dd. If that fails, try to parse
 * the string as a regular (long) timestamp.
 *///from  w w  w  .  j ava2s . c  o  m
@ConfigurableValue(valueType = "String", description = "Scenario start time of the bootstrap portion of a simulation")
public Competition withSimulationBaseTime(String baseTime) {
    Instant instant;
    try {
        DateTimeZone.setDefault(DateTimeZone.UTC);
        DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd");
        instant = fmt.parseDateTime(baseTime).toInstant();
    } catch (IllegalArgumentException e) {
        // Try to interpret the string as a long timestamp instead
        instant = new Instant(Long.parseLong(baseTime));
    }
    return withSimulationBaseTime(instant);
}