List of usage examples for java.text ParsePosition ParsePosition
public ParsePosition(int index)
From source file:auth.ProcessResponseServlet.java
private boolean validSamlDateFormat(String samlDate) { if (samlDate == null) { return false; }/*from w w w. j a va 2s. com*/ int indexT = samlDate.indexOf("T"); int indexZ = samlDate.indexOf("Z"); if (indexT != 10 || indexZ != 19) { return false; } String dateString = samlDate.substring(0, indexT); String timeString = samlDate.substring(indexT + 1, indexZ); SimpleDateFormat dayFormat = new SimpleDateFormat("yyyy-MM-dd"); SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss"); ParsePosition pos = new ParsePosition(0); Date parsedDate = dayFormat.parse(dateString, pos); pos = new ParsePosition(0); Date parsedTime = timeFormat.parse(timeString, pos); if (parsedDate == null || parsedTime == null) { return false; } return true; }
From source file:util.android.util.DateUtils.java
/** * Try to parse an ordinal date in the format: * <p>/* w ww . jav a 2 s . c o m*/ * Monday 1st July 2013 * <p> * SimpleDateFormat doesn't like st, nd, th, rd in dates so we modify the input String before processing. * * @param dateString * @param timezone * @return Date */ @SuppressLint("SimpleDateFormat") public static Date parseOrdinalDate(String dateString, TimeZone timezone) throws IllegalArgumentException { dateString = dateString.trim().replaceAll("([0-9]+)(?:st|nd|rd|th)?", "$1").replace(" ", " "); Date d = null; SimpleDateFormat sdf = new SimpleDateFormat(); for (String ordinalMask : ordinalMasks) { try { sdf.applyPattern(ordinalMask); sdf.setTimeZone(timezone); sdf.setLenient(true); d = sdf.parse(dateString, new ParsePosition(0)); if (d != null) break; } catch (Exception ignored) { } } if (d == null) throw new IllegalArgumentException(); return d; }
From source file:org.jumpmind.util.FormatUtils.java
public static Date parseDate(String str, String[] parsePatterns, TimeZone timeZone) { if (str == null || parsePatterns == null) { throw new IllegalArgumentException("Date and Patterns must not be null"); }// www.j a v a 2 s . co m SimpleDateFormat parser = null; ParsePosition pos = new ParsePosition(0); for (int i = 0; i < parsePatterns.length; i++) { if (i == 0) { parser = new SimpleDateFormat(parsePatterns[0]); if (timeZone != null) { parser.setTimeZone(timeZone); } } else { parser.applyPattern(parsePatterns[i]); } pos.setIndex(0); Date date = parser.parse(str, pos); if (date != null && pos.getIndex() == str.length()) { return date; } } try { Date date = new Date(Long.parseLong(str)); return date; } catch (NumberFormatException e) { } throw new ParseException("Unable to parse the date: " + str); }
From source file:easyJ.common.validate.GenericTypeValidator.java
/** * Checks if the value can safely be converted to a float primitive. * /*from w ww.j ava 2 s . com*/ * @param value * The value validation is being performed on. * @param locale * The locale to use to parse the number (system default if * null) * @return the converted Float value. */ public static Float formatFloat(String value, Locale locale) { Float result = null; if (value != null) { NumberFormat formatter = null; if (locale != null) { formatter = NumberFormat.getInstance(locale); } else { formatter = NumberFormat.getInstance(Locale.getDefault()); } ParsePosition pos = new ParsePosition(0); Number num = formatter.parse(value, pos); // If there was no error and we used the whole string if (pos.getErrorIndex() == -1 && pos.getIndex() == value.length()) { if (num.doubleValue() >= (Float.MAX_VALUE * -1) && num.doubleValue() <= Float.MAX_VALUE) { result = new Float(num.floatValue()); } } } return result; }
From source file:org.wings.SDimension.java
/** * Extract number from string./*from ww w. ja v a2s . co m*/ * * @return extracted integer. f.e.: "120px" becomes 120 or {@link #AUTO_INT} if <code>null</code> */ protected int extractNumericValue(String value) { if (value == null || value.equalsIgnoreCase(AUTO)) { return AUTO_INT; } else if (value.equalsIgnoreCase(INHERIT)) { return INHERIT_INT; } else { try { return new DecimalFormat().parse(value, new ParsePosition(0)).intValue(); } catch (Exception e) { return AUTO_INT; } } }
From source file:org.noorganization.instalistsynch.controller.synch.impl.CategorySynch.java
@Override public void indexLocal(int _groupId, Date _lastIndexTime) { String lastIndexTime = ISO8601Utils.format(_lastIndexTime, false, TimeZone.getTimeZone("GMT+0000"));//.concat("+0000"); boolean isLocal = false; GroupAuth groupAuth = mGroupAuthDbController.getLocalGroup(); if (groupAuth != null) { isLocal = groupAuth.getGroupId() == _groupId; }/*from w w w . java 2 s . co m*/ Cursor categoryLogCursor = mClientLogDbController.getLogsSince(lastIndexTime, mModelType); if (categoryLogCursor.getCount() == 0) { categoryLogCursor.close(); return; } try { while (categoryLogCursor.moveToNext()) { // fetch the action type int actionId = categoryLogCursor.getInt(categoryLogCursor.getColumnIndex(LogInfo.COLUMN.ACTION)); eActionType actionType = eActionType.getTypeById(actionId); List<ModelMapping> modelMappingList = mCategoryModelMappingController.get( ModelMapping.COLUMN.GROUP_ID + " = ? AND " + ModelMapping.COLUMN.CLIENT_SIDE_UUID + " LIKE ?", new String[] { String.valueOf(_groupId), categoryLogCursor .getString(categoryLogCursor.getColumnIndex(LogInfo.COLUMN.ITEM_UUID)) }); ModelMapping modelMapping = modelMappingList.size() == 0 ? null : modelMappingList.get(0); switch (actionType) { case INSERT: // skip insertion because this should be decided by the user if the non local groups should have access to the category // and also skip if a mapping for this case already exists! if (!isLocal || modelMapping != null) { continue; } String clientUuid = categoryLogCursor .getString(categoryLogCursor.getColumnIndex(LogInfo.COLUMN.ITEM_UUID)); Date clientDate = ISO8601Utils.parse( categoryLogCursor .getString(categoryLogCursor.getColumnIndex(LogInfo.COLUMN.ACTION_DATE)), new ParsePosition(0)); modelMapping = new ModelMapping(null, groupAuth.getGroupId(), null, clientUuid, new Date(Constants.INITIAL_DATE), clientDate, false); mCategoryModelMappingController.insert(modelMapping); break; case UPDATE: if (modelMapping == null) { Log.i(TAG, "indexLocal: the model is null but shouldn't be"); continue; } String timeString = categoryLogCursor .getString(categoryLogCursor.getColumnIndex(LogInfo.COLUMN.ACTION_DATE)); clientDate = ISO8601Utils.parse(timeString, new ParsePosition(0)); modelMapping.setLastClientChange(clientDate); mCategoryModelMappingController.update(modelMapping); break; case DELETE: if (modelMapping == null) { Log.i(TAG, "indexLocal: the model is null but shouldn't be"); continue; } modelMapping.setDeleted(true); timeString = categoryLogCursor .getString(categoryLogCursor.getColumnIndex(LogInfo.COLUMN.ACTION_DATE)); clientDate = ISO8601Utils.parse(timeString, new ParsePosition(0)); modelMapping.setLastClientChange(clientDate); mCategoryModelMappingController.update(modelMapping); break; default: } } } catch (Exception e) { categoryLogCursor.close(); } }
From source file:org.ms123.common.data.query.BasicSelectBuilder.java
protected Object getDate(Object data, Map<String, Object> rule) { try {//from w w w . j a v a 2s . co m Date d = new Date(); try { if (data instanceof Long) { d = new Date((Long) data); } else { d = new Date(Long.valueOf((String) rule.get("data"))); } } catch (Exception e) { try { if (data instanceof String) { d = new SimpleDateFormat( (((String) data).indexOf("T") > 0) ? "yyyy-MM-dd'T'HH:mm" : "yyyy-MM-dd") .parse((String) data, new ParsePosition(0)); } } catch (Exception e1) { System.out.println("E:" + e); } } data = ":param" + m_queryBuilder.getParamCount(); m_queryBuilder.getQueryParams().put("param" + m_queryBuilder.getParamCount(), d); m_queryBuilder.incParamCount(); } catch (Exception e) { e.printStackTrace(); data = "''"; } return data; }
From source file:net.sf.morph.transform.converters.TextToNumberConverter.java
/** * {@inheritDoc}//from w w w . j a v a 2s. co m */ protected Object convertImpl(Class destinationClass, Object source, Locale locale) throws Exception { if (ObjectUtils.isEmpty(source)) { return null; } // convert the source to a String String string = (String) getTextConverter().convert(String.class, source, locale); // // if a custom numberFormat has been specified, ues that for the // // conversion // if (numberFormat != null) { // Number number; // synchronized (numberFormat) { // number = numberFormat.parse(string); // } // // // convert the number to the destination class requested // return getNumberConverter().convert(destinationClass, number, // locale); // } StringBuffer charactersToParse = // remove characters that should be ignored, such as currency symbols // when currency handling is set to CURRENCY_IGNORE removeIgnoredCharacters(string, locale); // keep track of whether the conversion result needs to be negated // before it is returned boolean negate = handleParenthesesNegation(charactersToParse, locale); negate = negate || handleNegativeSignNegation(charactersToParse, locale); NumberFormat format = null; ParsePosition position = null; Number number = null; Object returnVal = null; String stringToParse = charactersToParse.toString(); // could not get this to work for some reason // // try to do the conversion assuming the source is a currency value // format = NumberFormat.getCurrencyInstance(locale); // position = new ParsePosition(0); // number = format.parse(stringWithoutIgnoredSymbolsStr, position); // if (isParseSuccessful(stringWithoutIgnoredSymbolsStr, position)) { // // convert the number to the destination class requested // returnVal = getNumberConverter().convert(destinationClass, number, // locale); // if (logger.isDebugEnabled()) { // logger.debug("Successfully parsed '" + source + "' as a currency value of " + returnVal); // } // return returnVal; // } // else { // if (logger.isDebugEnabled()) { // logger.debug("Could not perform conversion of '" + source + "' by treating the source as a currency value"); // } // } // try to do the conversion to decimal assuming the source is a // percentage if (getPercentageHandling() == PERCENTAGE_CONVERT_TO_DECIMAL) { format = NumberFormat.getPercentInstance(locale); position = new ParsePosition(0); number = format.parse(stringToParse, position); if (isParseSuccessful(stringToParse, position)) { // negate the number if needed returnVal = negateIfNecessary(number, negate, locale); // convert the number to the destination class requested returnVal = getNumberConverter().convert(destinationClass, returnVal, locale); if (logger.isDebugEnabled()) { logger.debug("Successfully parsed '" + source + "' as a percentage with value " + returnVal); } return returnVal; } if (logger.isDebugEnabled()) { logger.debug( "Could not perform conversion of '" + source + "' by treating the source as a percentage"); } } // try to do the conversion as a regular number format = NumberFormat.getInstance(locale); position = new ParsePosition(0); number = format.parse(stringToParse, position); if (isParseSuccessful(stringToParse, position)) { // negate the number if needed returnVal = negateIfNecessary(number, negate, locale); // convert the number to the destination class requested returnVal = getNumberConverter().convert(destinationClass, returnVal, locale); if (logger.isDebugEnabled()) { logger.debug("Successfully parsed '" + source + "' as a number or currency value of " + returnVal); } return returnVal; } if (logger.isDebugEnabled()) { logger.debug("Could not perform conversion of '" + source + "' by treating the source as a regular number or currency value"); } // // if the first character of the string is a currency symbol // if (Character.getType(stringWithoutIgnoredSymbolsStr.charAt(0)) == Character.CURRENCY_SYMBOL) { // // try doing the conversion as a regular number by stripping off the first character // format = NumberFormat.getInstance(locale); // position = new ParsePosition(1); // number = format.parse(stringWithoutIgnoredSymbolsStr, position); // if (isParseSuccessful(stringWithoutIgnoredSymbolsStr, position)) { // // convert the number to the destination class requested // return getNumberConverter().convert(destinationClass, number, // locale); // } // if (logger.isDebugEnabled()) { // logger.debug("Could not perform conversion of '" + source + "' by stripping the first character and treating as a normal number"); // } // } throw new TransformationException(destinationClass, source); }
From source file:org.wings.SDimension.java
/** * Tries to extract unit from passed string. I.e. returtn "px" if you pass "120px". * * @param value A compound number/unit string. May be <code>null</code> * @return The unit or <code>null</code> if not possible. *///from www .j a v a2s .c o m private String extractUnit(String value) { if (value == null) { return null; } else { ParsePosition position = new ParsePosition(0); try { new DecimalFormat().parse(value, position).intValue(); return value.substring(position.getIndex()).trim(); } catch (Exception e) { return null; } } }
From source file:com.arantius.tivocommander.Utils.java
private final static Date parseDateTimeStr(SimpleDateFormat dateParser, String dateStr) { TimeZone tz = TimeZone.getTimeZone("UTC"); dateParser.setTimeZone(tz);/* w w w. j a va 2 s. c om*/ ParsePosition pp = new ParsePosition(0); return dateParser.parse(dateStr, pp); }