Example usage for org.apache.commons.lang3.time DateUtils parseDateStrictly

List of usage examples for org.apache.commons.lang3.time DateUtils parseDateStrictly

Introduction

In this page you can find the example usage for org.apache.commons.lang3.time DateUtils parseDateStrictly.

Prototype

public static Date parseDateStrictly(final String str, final String... parsePatterns) throws ParseException 

Source Link

Document

Parses a string representing a date by trying a variety of different parsers.

The parse will try each parse pattern in turn.

Usage

From source file:de.tklerx.dao.Player.java

public Player(String playerName, String missedDate, String team, String history, String teamLink)
        throws ParseException {
    super();//w  ww.  j  a  v  a  2  s  . c o m
    this.playerName = playerName;
    Date date = DateUtils.parseDateStrictly(missedDate, new String[] { "dd.MM.yy HH:mm" });
    c.setTime(date);
    c.add(Calendar.DATE, 1);
    this.missedDate = c.getTime();
    this.team = team;
    this.history = history;
    this.teamLink = teamLink;
}

From source file:com.fanniemae.ezpie.common.StringUtilities.java

public static boolean isDate(String value) {
    try {/*from   w  w w.  j  av  a2  s .  c o m*/
        if (value == null) {
            return false;
        }
        DateUtils.parseDateStrictly(value, SUPPORTED_DATE_FORMATS);
        return true;
    } catch (ParseException ex) {
        return false;
    }
}

From source file:com.mingo.convert.ConversionUtils.java

/**
 * Convert string to date.//from   w ww.  ja  v a2s.  c  o  m
 *
 * @param source       date as string
 * @param datePatterns possible date patterns
 * @return date
 * @throws IllegalArgumentException
 */
public static Date convertToDate(String source, String... datePatterns) {
    try {
        return DateUtils.parseDateStrictly(source, datePatterns);
    } catch (ParseException e) {
        throw new IllegalArgumentException("Wrong date format. Possible formats: " + datePatterns, e);
    }
}

From source file:edu.harvard.iq.safe.lockss.impl.DaemonStatusDataUtil.java

/**
 *
 * @param timeStamp//from  w  w  w.  j a  v  a2  s . c om
 * @return
 */
/*
@Deprecated
public static long stringToEpocTime(String timeStamp) {
long epocTime = 0L;
DateFormat formater = null;
if (timeStamp.equals("never") || StringUtils.isEmpty(timeStamp)) {
    return epocTime;
}
try {
    formater = new SimpleDateFormat("HH:mm:ss MM/dd/yy");
            
    //logger.log(Level.INFO, "timeStamp=" + timeStamp);
    epocTime = ((Date) formater.parse(timeStamp)).getTime();//date.getTime();
    //logger.log(Level.INFO, "AuLastCrawl in long=" + epocTime);
} catch (java.text.ParseException ex) {
    epocTime = -1L;
    logger.log(Level.SEVERE, "date/time-string parsing error", ex);
} catch (Exception ex) {
    epocTime = -1L;
    logger.log(Level.SEVERE, "non-parsing error", ex);
}
        
return epocTime;
}
 */

public static long getEpocTimeFromString(String timestamp, String timezoneOffset) {
    long epocTime = 0L;
    String timestampWithTimezone = null;
    //FastDateFormat formater = null;
    if (StringUtils.isEmpty(timestamp) || timestamp.equals("never")) {
        return epocTime;
    }

    try {
        // timezoneOffset is externally given, box-wise
        // attach its timezone offset token (e.g., -0500)
        // to a timestamp to be evaluated so that it is correctly
        // converted at its correct timezone.
        if (StringUtils.isBlank(timezoneOffset)) {
            timestampWithTimezone = timestamp + getJVMTimezoneOffset();
            logger.log(Level.WARNING, "timezoneOffset is not available: use the JVM timezone={0}",
                    timestampWithTimezone);
        } else {
            timestampWithTimezone = timestamp + timezoneOffset;
        }

        logger.log(Level.FINEST, "After the timezone offset is attached to the timestamp={0}",
                timestampWithTimezone);
        // attach the Z format-token to 
        // the default lockssbox timestamp pattern
        String formatPatternForLockssTmstmpWTz = FORMAT_PATTERN_FOR_LOCKSSBOX_TMSTMP + " Z";

        epocTime = DateUtils.parseDateStrictly(timestampWithTimezone, formatPatternForLockssTmstmpWTz)
                .getTime();

        logger.log(Level.FINEST, "epoch time={0}", epocTime);
    } catch (java.text.ParseException ex) {
        epocTime = -1L;
        logger.log(Level.SEVERE, "date/time-string parsing error", ex);
    } catch (Exception ex) {
        epocTime = -1L;
        logger.log(Level.SEVERE, "non-parsing error", ex);
    }

    return epocTime;
}

From source file:com.fanniemae.ezpie.common.StringUtilities.java

public static Date toDate(String value, Date defaultValue) {
    try {// www. j  a  v  a 2 s.c  o  m
        if (value == null) {
            return defaultValue;
        }
        return DateUtils.parseDateStrictly(value, SUPPORTED_DATE_FORMATS);
    } catch (ParseException ex) {
        return defaultValue;
    }
}

From source file:edu.harvard.iq.safe.lockss.impl.DaemonStatusDataUtil.java

public static String calculateTimezoneOffset(String hdrTmstmpRaw, String tmstmpCurrentTime) {

    String timezoneOffset = null;
    try {//from   w  w w .j av  a2  s .com
        // working on the timestamp taken from the http response header
        // usually formatted liks this "01 Mar 2012 21:12:51 GMT";
        logger.log(Level.FINE, "Timestamp (timezone GMT) in Http Header={0}", hdrTmstmpRaw);
        // Since GMT is not recognized by DateUtils.parseDate() as GMT+0000,
        // replace it with +0000
        String hdrTmstmp = hdrTmstmpRaw.replace("GMT", TIMEZONE_GMT0);

        Date hdrGMTDate = DateUtils.parseDateStrictly(hdrTmstmp, FORMAT_PATTERN_FOR_HDR_TMSTMP);

        long hdrMillSec = hdrGMTDate.getTime();
        logger.log(Level.FINE, "timestamp in the header in UTC milliseconds={0}", hdrMillSec);

        // tmstmpCurrentTime, i.e., current-time timestamp taken from the 
        // PlatformStatus page is formatted like: "16:12:51 03/01/12";

        logger.log(Level.FINE, "local-time timestamp {0} by the lockss box=", tmstmpCurrentTime);

        // append the timezone token to the format pattern to make sure
        // the parser uses the GMT+0000 timezone
        String formatPatternForLockssTmstmpWTz = FORMAT_PATTERN_FOR_LOCKSSBOX_TMSTMP + " Z";

        Date currentLocalTime = DateUtils.parseDate(tmstmpCurrentTime + " " + TIMEZONE_GMT0,
                formatPatternForLockssTmstmpWTz);

        Long currentLocalTimeMillSec = currentLocalTime.getTime();
        logger.log(Level.FINE, "Resulting time in UTC milliseconds={0}", currentLocalTimeMillSec);

        // take the difference betwen header and curret-time timestamp
        Long offsetToGMTMillSec = currentLocalTimeMillSec - hdrMillSec;
        logger.log(Level.FINE, "diff in millis={0}", offsetToGMTMillSec);

        Long offsetToGMTmin = TimeUnit.MILLISECONDS.toMinutes(offsetToGMTMillSec);
        logger.log(Level.FINE, "offset To GMT in min={0}", offsetToGMTmin);

        Long hPart = 0L;
        Long mPart = 0L;
        // remove the sign from the min part to avoid a case like -04-30
        mPart = Math.abs(offsetToGMTmin % 60L);
        hPart = offsetToGMTmin / 60L;
        timezoneOffset = getUTCOffsetString(hPart, mPart);
        logger.log(Level.FINE, "timezone offset to be used for this lockss box={0}", timezoneOffset);
    } catch (ParseException ex) {
        logger.log(Level.SEVERE, "failed to parse the givne timestamp", ex);
    } finally {
        if (StringUtils.isBlank(timezoneOffset)) {
            timezoneOffset = getJVMTimezoneOffset();
        }
    }
    return timezoneOffset;
}

From source file:org.apache.cassandra.serializers.TimestampSerializer.java

public static long dateStringToTimestamp(String source) throws MarshalException {
    if (source.equalsIgnoreCase("now"))
        return System.currentTimeMillis();

    // Milliseconds since epoch?
    if (timestampPattern.matcher(source).matches()) {
        try {//from   w  ww .jav  a 2s  .com
            return Long.parseLong(source);
        } catch (NumberFormatException e) {
            throw new MarshalException(String.format("Unable to make long (for date) from: '%s'", source), e);
        }
    }

    // Last chance, attempt to parse as date-time string
    try {
        return DateUtils.parseDateStrictly(source, dateStringPatterns).getTime();
    } catch (ParseException e1) {
        throw new MarshalException(String.format("Unable to coerce '%s' to a formatted date (long)", source),
                e1);
    }
}

From source file:org.gvnix.web.datatables.util.QuerydslUtils.java

/**
 * Return an expression for {@code entityPath.fieldName} (for Dates) with
 * the {@code operator} or "equal" by default.
 * <p/>/*w w w.j a va 2s.  co m*/
 * Expr: {@code entityPath.fieldName eq searchObj}
 * 
 * @param entityPath
 * @param fieldName
 * @param searchObj
 * @param operator
 * @param fieldType
 * @return
 */
@SuppressWarnings("unchecked")
public static <T> BooleanExpression createDateExpression(PathBuilder<T> entityPath, String fieldName,
        Object searchObj, String operator, Class<?> fieldType) {
    DatePath<Date> dateExpression = entityPath.getDate(fieldName, (Class<Date>) fieldType);
    try {
        Date value = DateUtils.parseDateStrictly((String) searchObj, FULL_DATE_PATTERNS);
        if (StringUtils.equalsIgnoreCase(operator, OPERATOR_GOE)) {
            return dateExpression.goe(value);
        } else if (StringUtils.equalsIgnoreCase(operator, "gt")
                || StringUtils.equalsIgnoreCase(operator, "after")) {
            return dateExpression.gt(value);
        } else if (StringUtils.equalsIgnoreCase(operator, OPERATOR_LOE)) {
            return dateExpression.loe(value);
        } else if (StringUtils.equalsIgnoreCase(operator, "lt")
                || StringUtils.equalsIgnoreCase(operator, "before")) {
            return dateExpression.lt(value);
        }
    } catch (ParseException e) {
        return entityPath.get(fieldName).eq(searchObj);
    }
    return entityPath.get(fieldName).eq(searchObj);
}

From source file:org.gvnix.web.datatables.util.QuerydslUtils.java

/**
 * Return where clause expression for date properties, trying to parse the
 * value to find to date and comparing it to the value of the date; if the
 * value to find cannot be parsed to date, then try to cast the value to
 * string before check it./*w w  w  .j  a  va2 s  .c  o m*/
 * <p/>
 * <ul>
 * <li>
 * If value to find {@code searchStr} can be parsed using the patterns
 * <em>dd-MM-yyyy HH:mm:ss</em> or <em>dd-MM-yyyy HH:mm</em> or
 * <em>dd-MM-yyyy</em> to {@code searchDate}, then search by specific date:
 * <p/>
 * - Querydsl Expr: {@code entityPath.fieldName = searchDate}
 * <p/>
 * - Database operation: {@code entity.fieldName = searchDate}</li>
 * <li>
 * If value to find {@code searchStr} can be parsed using the pattern
 * <em>dd-MM</em> to {@code searchDate}, then search by specific day and
 * month:
 * <p/>
 * - Querydsl Expr:
 * {@code entityPath.fieldName.dayOfMonth() = searchDate.day and entityPath.fieldName.month() = searchDate.month}
 * <p/>
 * - Database operation:
 * {@code dayofmonth(entity.fieldName) = searchDate.day && month(entity.fieldName) = searchDate.month}
 * </li>
 * <li>
 * If value to find {@code searchStr} can be parsed using the pattern
 * <em>MM-aaaa</em> to {@code searchDate}, then obtain the first day of the
 * month for that year and the last day of the month for that year and check
 * that value is into between theses values:
 * <p/>
 * - Querydsl Expr:
 * {@code entityPath.fieldName.between(searchDate.firstDayOfMonth, searchDate.lastDayOfMonth)}
 * <p/>
 * - Database operation:
 * {@code entity.fieldName between searchDate.firstDayOfMonth and searchDate.lastDayOfMonth}
 * </li>
 * <li>
 * If value to find cannot be parsed as date, then try to cast the value to
 * string before check it:
 * <p/>
 * - Querydsl Expr:
 * {@code entityPath.fieldName.stringValue() like ('%' + searchStr + '%')}
 * <p/>
 * - Database operation:
 * {@code str(entity.fieldName) like ('%' + searchStr + '%')}
 * <p/>
 * Note that like operation is case sensitive.</li>
 * </ul>
 * 
 * @param entityPath Full path to entity and associations. For example:
 *        {@code Pet} , {@code Pet.owner}
 * @param fieldName Property name in the given entity path. For example:
 *        {@code weight} in {@code Pet} entity, {@code age} in
 *        {@code Pet.owner} entity.
 * @param searchStr the value to find, may be null
 * @return PredicateOperation
 */
public static <T, C extends java.lang.Comparable<?>> BooleanExpression createDateExpression(
        PathBuilder<T> entityPath, String fieldName, Class<C> fieldType, String searchStr) {
    if (StringUtils.isEmpty(searchStr)) {
        return null;
    }

    DatePath<C> dateExpression = entityPath.getDate(fieldName, fieldType);

    BooleanExpression expression;

    // Search by full date
    String[] parsePatterns = null;
    try {
        parsePatterns = FULL_DATE_PATTERNS_WITH_TIME;
        Date searchDate = DateUtils.parseDateStrictly(searchStr, parsePatterns);
        Calendar searchCal = Calendar.getInstance();
        searchCal.setTime(searchDate);
        expression = dateExpression.eq((fieldType.cast(searchCal)));
    } catch (Exception e) {
        // do nothing, and try the next parsing
        expression = null;
    }

    if (expression == null) {
        try {
            parsePatterns = FULL_DATE_PAT_WO_TIME;
            Date searchDate = DateUtils.parseDateStrictly(searchStr, parsePatterns);
            Calendar searchCal = Calendar.getInstance();
            searchCal.setTime(searchDate);
            expression = dateExpression.dayOfMonth().eq(searchCal.get(Calendar.DAY_OF_MONTH))
                    .and(dateExpression.month().eq(searchCal.get(Calendar.MONTH) + 1))
                    .and(dateExpression.year().eq(searchCal.get(Calendar.YEAR)));
        } catch (Exception e) {
            // do nothing, and try the next parsing
            expression = null;
        }
    }

    if (expression == null) {
        // Search by day and month
        parsePatterns = DAY_AND_MONTH_DATE_PATTERNS;
        try {
            Date searchDate = DateUtils.parseDateStrictly(searchStr, parsePatterns);
            Calendar searchCal = Calendar.getInstance();
            searchCal.setTime(searchDate);
            expression = dateExpression.dayOfMonth().eq(searchCal.get(Calendar.DAY_OF_MONTH))
                    .and(dateExpression.month().eq(searchCal.get(Calendar.MONTH) + 1));
        } catch (Exception e) {
            // do nothing, and try the next parsing
            expression = null;
        }
    }

    // Search by month and year
    if (expression == null) {
        parsePatterns = MONTH_AND_YEAR_DATE_PATTERNS;
        try {
            Date searchDate = DateUtils.parseDateStrictly(searchStr, parsePatterns);
            Calendar searchCal = Calendar.getInstance();
            searchCal.setTime(searchDate);

            // from 1st day of the month
            Calendar monthStartCal = Calendar.getInstance();
            monthStartCal.set(searchCal.get(Calendar.YEAR), searchCal.get(Calendar.MONTH), 1, 23, 59, 59);
            monthStartCal.set(Calendar.MILLISECOND, 999);

            // to last day of the month
            Calendar monthEndCal = Calendar.getInstance();
            monthEndCal.set(searchCal.get(Calendar.YEAR), (searchCal.get(Calendar.MONTH) + 1), 1, 23, 59, 59);
            monthEndCal.set(Calendar.MILLISECOND, 999);

            expression = dateExpression.between(fieldType.cast(monthStartCal), fieldType.cast(monthEndCal));
        } catch (Exception e) {
            // do nothing, and try the next parsing
            expression = null;
        }
    }

    // Search by year
    // NOT NEEDED; JUST USE DEFAULT EXPRESSION
    if (expression == null) {
        // Default expression
        expression = dateExpression.stringValue().like("%".concat(searchStr).concat("%"));
    }

    return expression;
}

From source file:org.jasig.ssp.util.importer.job.validation.map.metadata.database.MapColumnMetadata.java

public Object convertValueToType(String columnValue, MapReference mapReference,
        DatabaseConstraintMapValidationContext validation) {
    Object propertyValue = null;/*from w  w  w.j av a  2s .com*/
    String typeAsString = "";
    if (columnValue != null) {
        try {
            switch (javaSqlType) {
            case Types.BIGINT:
                typeAsString = "BIGINT";
                propertyValue = Long.parseLong(columnValue);
                break;
            case Types.INTEGER:
                typeAsString = "INTEGER";
                propertyValue = Integer.parseInt(columnValue);
                break;
            case Types.DECIMAL:
                typeAsString = "DECIMAL";
            case Types.DOUBLE:
                typeAsString = "DOUBLE";
            case Types.FLOAT:
                typeAsString = "FLOAT";
            case Types.NUMERIC:
                typeAsString = "NUMERIC";
                propertyValue = new BigDecimal(columnValue);
                break;

            case Types.DATE:
                typeAsString = "DATE";
                propertyValue = DateUtils.parseDateStrictly(columnValue, DATE_PATTERNS);
                break;
            case Types.TIMESTAMP:
                typeAsString = "TIMESTAMP";
                propertyValue = new java.sql.Timestamp(Long.getLong(columnValue));
                break;
            case Types.TIME:
                typeAsString = "TIME";
                propertyValue = new Time(DateUtils.parseDateStrictly(columnValue, TIME_PATTERNS).getTime());
                break;
            default:
                typeAsString = javaSqlType.toString();
                propertyValue = columnValue;
                break;

            }
        } catch (Exception exception) {
            validation.addViolation(new UnableToParseMapViolation(mapReference, columnValue, typeAsString));
            propertyValue = columnValue;
        }

    }
    return propertyValue;
}