Example usage for java.text DateFormat parse

List of usage examples for java.text DateFormat parse

Introduction

In this page you can find the example usage for java.text DateFormat parse.

Prototype

public Date parse(String source) throws ParseException 

Source Link

Document

Parses text from the beginning of the given string to produce a date.

Usage

From source file:com.sun.socialsite.util.DateUtil.java

/**
 * Returns a Date using the passed-in string and format.  Returns null if the string
 * is null or empty or if the format is null.  The string must match the format.
 **//*from  w w  w . j  a v  a 2 s.  c  o  m*/
public static Date parse(String aValue, DateFormat aFormat) throws ParseException {
    if (StringUtils.isEmpty(aValue) || aFormat == null) {
        return null;
    }
    synchronized (aFormat) {
        return aFormat.parse(aValue);
    }
}

From source file:net.netheos.pcsapi.providers.hubic.Swift.java

static Date parseLastModified(JSONObject json) {
    try {//from  w w  w.java 2  s .c o  m
        String lm = json.optString("last_modified", null); // "2014-02-12T16:13:49.346540"
        if (lm == null) {
            return null;
        }

        // Date format
        if (!lm.contains("+")) {
            lm += "+0000";
        }

        // Normalize millis and remove microseconds, if any:
        StringBuilder builder = new StringBuilder(lm);
        int dotPos = lm.indexOf('.');
        int plusPos = lm.indexOf('+');
        if (dotPos > 0) {
            if (plusPos - dotPos > 4) {
                builder.delete(dotPos + 4, plusPos); // remove microsec
            } else
                while (plusPos - dotPos < 4) { // complete millis : ".3" -> ".300"
                    builder.insert(plusPos, '0');
                    plusPos++;
                }
        } else { // no milliseconds ? defensive code
            builder.insert(plusPos, ".000");
        }
        DateFormat lastModifiedDateFormat = new SimpleDateFormat(DF_LAST_MODIFIED_PATTERN, Locale.ENGLISH);
        return lastModifiedDateFormat.parse(builder.toString());

    } catch (ParseException ex) {
        LOGGER.warn("Error parsing date", ex);
        return null;
    }
}

From source file:com.jeeframework.util.validate.GenericTypeValidator.java

/**
 *  <p>/*from   w  w w.ja  v  a 2  s  .  c  om*/
 *
 *  Checks if the field is a valid date. The <code>Locale</code> is used
 *  with <code>java.text.DateFormat</code>. The setLenient method is set to
 *  <code>false</code> for all.</p>
 *
 *@param  value   The value validation is being performed on.
 *@param  locale  The Locale to use to parse the date (system default if
 *      null)
 *@return the converted Date value.
 */
public static Date formatDate(String value, Locale locale) {
    Date date = null;

    if (value == null) {
        return null;
    }

    try {
        DateFormat formatter = null;
        if (locale != null) {
            formatter = DateFormat.getDateInstance(DateFormat.SHORT, locale);
        } else {
            formatter = DateFormat.getDateInstance(DateFormat.SHORT, Locale.getDefault());
        }

        formatter.setLenient(false);

        date = formatter.parse(value);
    } catch (ParseException e) {
        // Bad date so return null
        Log log = LogFactory.getLog(GenericTypeValidator.class);
        if (log.isDebugEnabled()) {
            log.debug("Date parse failed value=[" + value + "], " + "locale=[" + locale + "] " + e);
        }
    }

    return date;
}

From source file:com.amalto.core.storage.StorageMetadataUtils.java

public static Object convert(String dataAsString, String type) {
    if (Types.STRING.equals(type) || Types.TOKEN.equals(type) || Types.DURATION.equals(type)) {
        return dataAsString;
    } else if (Types.INTEGER.equals(type) || Types.POSITIVE_INTEGER.equals(type)
            || Types.NEGATIVE_INTEGER.equals(type) || Types.NON_NEGATIVE_INTEGER.equals(type)
            || Types.NON_POSITIVE_INTEGER.equals(type) || Types.INT.equals(type)
            || Types.UNSIGNED_INT.equals(type)) {
        return Integer.parseInt(dataAsString);
    } else if (Types.DATE.equals(type)) {
        // Be careful here: DateFormat is not thread safe
        synchronized (DateConstant.DATE_FORMAT) {
            try {
                DateFormat dateFormat = DateConstant.DATE_FORMAT;
                Date date = dateFormat.parse(dataAsString);
                return new Timestamp(date.getTime());
            } catch (Exception e) {
                throw new RuntimeException("Could not parse date string", e);
            }/*from ww  w  .  ja v  a 2s . com*/
        }
    } else if (Types.DATETIME.equals(type)) {
        // Be careful here: DateFormat is not thread safe
        synchronized (DateTimeConstant.DATE_FORMAT) {
            try {
                DateFormat dateFormat = DateTimeConstant.DATE_FORMAT;
                Date date = dateFormat.parse(dataAsString);
                return new Timestamp(date.getTime());
            } catch (Exception e) {
                throw new RuntimeException("Could not parse date time string", e);
            }
        }
    } else if (Types.BOOLEAN.equals(type)) {
        // Boolean.parseBoolean returns "false" if content isn't a boolean string value. Callers of this method
        // expect call to fail if data is malformed.
        if ("0".equals(dataAsString)) { //$NON-NLS-1$
            return false;
        } else if ("1".equals(dataAsString)) { //$NON-NLS-1$
            return true;
        }
        if (!"false".equalsIgnoreCase(dataAsString) && !"true".equalsIgnoreCase(dataAsString)) { //$NON-NLS-1$ //$NON-NLS-2$
            throw new IllegalArgumentException("Value '" + dataAsString + "' is not valid for boolean");
        }
        return Boolean.parseBoolean(dataAsString);
    } else if (Types.DECIMAL.equals(type)) {
        try {
            return new BigDecimal(dataAsString);
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("'" + dataAsString + "' is not a number.", e);
        }
    } else if (Types.FLOAT.equals(type)) {
        return Float.parseFloat(dataAsString);
    } else if (Types.LONG.equals(type) || Types.UNSIGNED_LONG.equals(type)) {
        return Long.parseLong(dataAsString);
    } else if (Types.ANY_URI.equals(type)) {
        return dataAsString;
    } else if (Types.SHORT.equals(type) || Types.UNSIGNED_SHORT.equals(type)) {
        return Short.parseShort(dataAsString);
    } else if (Types.QNAME.equals(type)) {
        return dataAsString;
    } else if (Types.BASE64_BINARY.equals(type)) {
        return dataAsString;
    } else if (Types.HEX_BINARY.equals(type)) {
        return dataAsString;
    } else if (Types.BYTE.equals(type) || Types.UNSIGNED_BYTE.equals(type)) {
        return Byte.parseByte(dataAsString);
    } else if (Types.DOUBLE.equals(type) || Types.UNSIGNED_DOUBLE.equals(type)) {
        return Double.parseDouble(dataAsString);
    } else if (Types.TIME.equals(type)) {
        // Be careful here: DateFormat is not thread safe
        synchronized (TimeConstant.TIME_FORMAT) {
            try {
                DateFormat dateFormat = TimeConstant.TIME_FORMAT;
                Date date = dateFormat.parse(dataAsString);
                return new Timestamp(date.getTime());
            } catch (ParseException e) {
                throw new RuntimeException("Could not parse time string", e);
            }
        }
    } else {
        throw new NotImplementedException("No support for type '" + type + "'");
    }
}

From source file:com.esri.geoevent.solutions.adapter.cot.CoTUtilities.java

public static Date parseCoTDate(String dateString) throws Exception {
    if (!dateString.isEmpty()) {
        DateFormat formatter1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SS'Z'");
        formatter1.setTimeZone(TimeZone.getTimeZone("Zulu"));
        DateFormat formatter2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
        formatter2.setTimeZone(TimeZone.getTimeZone("Zulu"));
        Date date = null;/*from   w ww. j  a  v  a 2s  .  co  m*/
        try {
            if (date == null)
                date = (Date) formatter1.parse(dateString);
        } catch (ParseException ex) {
        }
        try {
            if (date == null)
                date = (Date) formatter2.parse(dateString);
        } catch (ParseException ex) {
        }
        return date;
    }
    return null;
}

From source file:org.dasein.cloud.terremark.Terremark.java

public static Date parseIsoDate(String isoDateString) {
    java.text.DateFormat df = new SimpleDateFormat(ISO8601_PATTERN);
    df.setTimeZone(TimeZone.getTimeZone("UTC"));
    Date result = null;//from w ww  . ja v  a2s  . co m
    try {
        result = df.parse(isoDateString);
    } catch (ParseException e) {
        df = new SimpleDateFormat(ISO8601_NO_MS_PATTERN);
        df.setTimeZone(TimeZone.getTimeZone("UTC"));
        result = null;
        try {
            result = df.parse(isoDateString);
        } catch (ParseException e2) {
            e2.printStackTrace();
        }
    }
    return result;
}

From source file:com.cloud.api.ApiDispatcher.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private static void setFieldValue(Field field, BaseCmd cmdObj, Object paramObj, Parameter annotation)
        throws IllegalArgumentException, ParseException {
    try {//  w ww.ja  va  2 s .c  o  m
        field.setAccessible(true);
        CommandType fieldType = annotation.type();
        switch (fieldType) {
        case BOOLEAN:
            field.set(cmdObj, Boolean.valueOf(paramObj.toString()));
            break;
        case DATE:
            // This piece of code is for maintaining backward compatibility
            // and support both the date formats(Bug 9724)
            // Do the date messaging for ListEventsCmd only
            if (cmdObj instanceof ListEventsCmd) {
                boolean isObjInNewDateFormat = isObjInNewDateFormat(paramObj.toString());
                if (isObjInNewDateFormat) {
                    DateFormat newFormat = BaseCmd.NEW_INPUT_FORMAT;
                    synchronized (newFormat) {
                        field.set(cmdObj, newFormat.parse(paramObj.toString()));
                    }
                } else {
                    DateFormat format = BaseCmd.INPUT_FORMAT;
                    synchronized (format) {
                        Date date = format.parse(paramObj.toString());
                        if (field.getName().equals("startDate")) {
                            date = messageDate(date, 0, 0, 0);
                        } else if (field.getName().equals("endDate")) {
                            date = messageDate(date, 23, 59, 59);
                        }
                        field.set(cmdObj, date);
                    }
                }
            } else {
                DateFormat format = BaseCmd.INPUT_FORMAT;
                format.setLenient(false);
                synchronized (format) {
                    field.set(cmdObj, format.parse(paramObj.toString()));
                }
            }
            break;
        case FLOAT:
            // Assuming that the parameters have been checked for required before now,
            // we ignore blank or null values and defer to the command to set a default
            // value for optional parameters ...
            if (paramObj != null && isNotBlank(paramObj.toString())) {
                field.set(cmdObj, Float.valueOf(paramObj.toString()));
            }
            break;
        case INTEGER:
            // Assuming that the parameters have been checked for required before now,
            // we ignore blank or null values and defer to the command to set a default
            // value for optional parameters ...
            if (paramObj != null && isNotBlank(paramObj.toString())) {
                field.set(cmdObj, Integer.valueOf(paramObj.toString()));
            }
            break;
        case LIST:
            List listParam = new ArrayList();
            StringTokenizer st = new StringTokenizer(paramObj.toString(), ",");
            while (st.hasMoreTokens()) {
                String token = st.nextToken();
                CommandType listType = annotation.collectionType();
                switch (listType) {
                case INTEGER:
                    listParam.add(Integer.valueOf(token));
                    break;
                case UUID:
                    if (token.isEmpty())
                        break;
                    Long internalId = translateUuidToInternalId(token, annotation);
                    listParam.add(internalId);
                    break;
                case LONG: {
                    listParam.add(Long.valueOf(token));
                }
                    break;
                case SHORT:
                    listParam.add(Short.valueOf(token));
                case STRING:
                    listParam.add(token);
                    break;
                }
            }
            field.set(cmdObj, listParam);
            break;
        case UUID:
            if (paramObj.toString().isEmpty())
                break;
            Long internalId = translateUuidToInternalId(paramObj.toString(), annotation);
            field.set(cmdObj, internalId);
            break;
        case LONG:
            field.set(cmdObj, Long.valueOf(paramObj.toString()));
            break;
        case SHORT:
            field.set(cmdObj, Short.valueOf(paramObj.toString()));
            break;
        case STRING:
            if ((paramObj != null) && paramObj.toString().length() > annotation.length()) {
                s_logger.error("Value greater than max allowed length " + annotation.length() + " for param: "
                        + field.getName());
                throw new InvalidParameterValueException("Value greater than max allowed length "
                        + annotation.length() + " for param: " + field.getName());
            }
            field.set(cmdObj, paramObj.toString());
            break;
        case TZDATE:
            field.set(cmdObj, DateUtil.parseTZDateString(paramObj.toString()));
            break;
        case MAP:
        default:
            field.set(cmdObj, paramObj);
            break;
        }
    } catch (IllegalAccessException ex) {
        s_logger.error("Error initializing command " + cmdObj.getCommandName() + ", field " + field.getName()
                + " is not accessible.");
        throw new CloudRuntimeException("Internal error initializing parameters for command "
                + cmdObj.getCommandName() + " [field " + field.getName() + " is not accessible]");
    }
}

From source file:com.radvision.icm.service.vcm.ICMService.java

private static long getCurrentDate(long time) throws Exception {
    Date dt = new Date(time);
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    String s = df.format(dt);//from  w ww .j av  a2  s  .  c om
    Date dtNew = df.parse(s);
    return dtNew.getTime();
}

From source file:com.jts.rest.profileservice.utils.RestServiceHelper.java

/**
 * Uses MemberChallenge service to get all the associated challenge information for a user
 * Sorts the challenge information with end date
 * Returns all the active challenges and 3 most recent past challenge 
 * @param sessionId/*from  w ww . ja  v  a  2 s.  co  m*/
 * @param username
 * @return
 * @throws MalformedURLException
 * @throws IOException
 */
@SuppressWarnings("unchecked")
public static JSONObject getProcessedChallengesM1(String sessionId, String username)
        throws MalformedURLException, IOException {
    //get all challenges
    JSONArray challenges = getChallenges(sessionId, username);

    JSONArray activeChallenges = new JSONArray();
    JSONArray pastChallenges = new JSONArray();
    SortedMap<Long, JSONObject> pastChallengesByDate = new TreeMap<Long, JSONObject>();
    Iterator<JSONObject> iterator = challenges.iterator();

    DateFormat dateFormat = new SimpleDateFormat("yyyy-mm-ddhh:mm:ss");

    while (iterator.hasNext()) {
        JSONObject challenge = iterator.next();
        //identify active challenge with status
        if (challenge.get("Status__c").equals(PSContants.STATUS_CREATED)) {
            activeChallenges.add(challenge);
        } else {
            String endDateStr = ((String) challenge.get("End_Date__c")).replace("T", "");
            Date date = new Date();
            try {
                date = dateFormat.parse(endDateStr);
            } catch (ParseException pe) {
                logger.log(Level.SEVERE, "Error occurent while parsing date " + endDateStr);
            }
            pastChallengesByDate.put(date.getTime(), challenge);
        }
    }

    //from the sorted map extract the recent challenge
    int pastChallengeSize = pastChallengesByDate.size();
    if (pastChallengeSize > 0) {
        Object[] challengeArr = (Object[]) pastChallengesByDate.values().toArray();
        int startIndex = pastChallengeSize > 3 ? pastChallengeSize - 3 : 0;
        for (int i = startIndex; i < pastChallengeSize; i++) {
            pastChallenges.add(challengeArr[i]);
        }
    }
    JSONObject resultChallenges = new JSONObject();
    resultChallenges.put("activeChallenges", activeChallenges);
    resultChallenges.put("pastChallenges", pastChallenges);
    resultChallenges.put("totalChallenges", challenges.size());
    return resultChallenges;
}

From source file:gobblin.data.management.conversion.hive.validation.ValidationJob.java

public static Long getPartitionCreateTime(String partitionName) throws ParseException {
    String dateString = null;//from  w  w  w.  ja  v a  2 s  .c o  m
    for (String st : SLASH_SPLITTER.splitToList(partitionName)) {
        if (st.startsWith(DATEPARTITION)) {
            dateString = EQUALITY_SPLITTER.splitToList(st).get(1);
        }
    }
    Preconditions.checkNotNull(dateString, "Unable to get partition date");
    DateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
    return dateFormat.parse(dateString).getTime();
}