Example usage for java.text SimpleDateFormat setLenient

List of usage examples for java.text SimpleDateFormat setLenient

Introduction

In this page you can find the example usage for java.text SimpleDateFormat setLenient.

Prototype

public void setLenient(boolean lenient) 

Source Link

Document

Specify whether or not date/time parsing is to be lenient.

Usage

From source file:fr.paris.lutece.plugins.crm.web.CRMApp.java

/**
 * Check the format of the filter modification date
 * @throws SiteMessageException/*  w  w  w .  j  av a  2 s  .  co m*/
 */
private Date checkFormatModificationDateFilter(String strModificationDate, HttpServletRequest request)
        throws SiteMessageException {
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    sdf.setLenient(true);

    Date d = new Date();

    try {
        d = sdf.parse(strModificationDate);
    } catch (Exception e) {
        SiteMessageService.setMessage(request, CRMConstants.MESSAGE_INVALID_FORMAT_DATE_MODIFICATION);
    }

    String t = sdf.format(d);

    if (t.compareTo(strModificationDate) != 0) {
        SiteMessageService.setMessage(request, CRMConstants.MESSAGE_INVALID_FORMAT_DATE_MODIFICATION);
    }

    return d;
}

From source file:com.s3d.webapps.util.time.DateUtils.java

/**
 * <p>Parses a string representing a date by trying a variety of different parsers.</p>
 * //from   w w  w .j  a v  a 2s . c  om
 * <p>The parse will try each parse pattern in turn.
 * A parse is only deemed successful if it parses the whole of the input string.
 * If no parse patterns match, a ParseException is thrown.</p>
 * 
 * @param str  the date to parse, not null
 * @param parsePatterns  the date format patterns to use, see SimpleDateFormat, not null
 * @param lenient Specify whether or not date/time parsing is to be lenient.
 * @return the parsed date
 * @throws IllegalArgumentException if the date string or pattern array is null
 * @throws ParseException if none of the date patterns were suitable
 * @see java.util.Calender#isLenient()
 */
private static Date parseDateWithLeniency(String str, String[] parsePatterns, boolean lenient)
        throws ParseException {
    if (str == null || parsePatterns == null) {
        throw new IllegalArgumentException("Date and Patterns must not be null");
    }

    SimpleDateFormat parser = new SimpleDateFormat();
    parser.setLenient(lenient);
    ParsePosition pos = new ParsePosition(0);
    for (int i = 0; i < parsePatterns.length; i++) {

        String pattern = parsePatterns[i];

        // LANG-530 - need to make sure 'ZZ' output doesn't get passed to SimpleDateFormat
        if (parsePatterns[i].endsWith("ZZ")) {
            pattern = pattern.substring(0, pattern.length() - 1);
        }

        parser.applyPattern(pattern);
        pos.setIndex(0);

        String str2 = str;
        // LANG-530 - need to make sure 'ZZ' output doesn't hit SimpleDateFormat as it will ParseException
        if (parsePatterns[i].endsWith("ZZ")) {
            int signIdx = indexOfSignChars(str2, 0);
            while (signIdx >= 0) {
                str2 = reformatTimezone(str2, signIdx);
                signIdx = indexOfSignChars(str2, ++signIdx);
            }
        }

        Date date = parser.parse(str2, pos);
        if (date != null && pos.getIndex() == str2.length()) {
            return date;
        }
    }
    throw new ParseException("Unable to parse the date: " + str, -1);
}

From source file:edu.wustl.bulkoperator.processor.CustomDateConverter.java

public Object convert(Class type, Object value) {
    SimpleDateFormat format = null;
    String formatString = null;/*  w ww  .  java 2  s.co  m*/
    String dateValue = null;
    Date date = null;
    if (value instanceof DateValue) {
        formatString = ((DateValue) value).getFormat();
        dateValue = ((DateValue) value).getValue();
    } else {
        dateValue = value.toString();
        if (dateValue.contains("-")) {
            formatString = DEFAULT_FORMAT_HIFEN;
        } else if (dateValue.contains("/")) {
            formatString = DEFAULT_FORMAT_SLASH;
        }

    }
    try {
        if (formatString.contains(":") && dateValue != null && !dateValue.contains(":")) {
            dateValue = dateValue + " 00:00";
        }
        format = new SimpleDateFormat(formatString);
        format.setLenient(false);
        date = format.parse(dateValue);
    } catch (ParseException e) {

        logger.error("Error while parsing date.", e);
    }
    return date;
}

From source file:com.snaptic.api.SnapticAPI.java

private long parse3339(String time) {
    if (time == null || time.length() == 0) {
        return 0;
    }/*  w ww  .j a v a  2 s .c o m*/

    if (timestamper != null) {
        try {
            timestamper.parse3339(time);
        } catch (TimeFormatException e) {
            log("caught a TimeFormatException parsing timestamp: \"" + time + '"');
            e.printStackTrace();
            return 0;
        }

        return timestamper.normalize(false);
    } else {
        Date timestamp = new Date();

        SimpleDateFormat rfc3339 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
        rfc3339.setLenient(true);

        try {
            timestamp = rfc3339.parse(time);
        } catch (ParseException e) {
            log("caught a ParseException parsing timestamp: \"" + time + '"');
            e.printStackTrace();
            return 0;
        }

        return timestamp.getTime();
    }
}

From source file:com.archsystemsinc.ipms.sec.webapp.controller.MeetingController.java

@Override
@InitBinder//from  w ww . j  av  a  2s.c o  m
public void initBinder(final WebDataBinder binder) {
    final SimpleDateFormat dateFormat = new SimpleDateFormat(GenericConstants.DEFAULT_DATE_FORMAT);
    dateFormat.setLenient(false);
    // true passed to CustomDateEditor constructor means convert empty
    // String to null
    binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    final NumberFormat numberFormat = NumberFormat.getInstance();
    binder.registerCustomEditor(Float.class, new CustomNumberEditor(Float.class, numberFormat, true));

}

From source file:gov.nih.nci.ncicb.tcga.dcc.datareports.service.PendingUUIDProcessor.java

/**
 * validate shipped Date/*  w  ww  .jav a  2s  . co m*/
 *
 * @param plateId
 * @return true if validation passes
 */
protected boolean validateShippedDate(final JSONObject plateId) {
    boolean retValue = true;
    if (checkElementExistence(SHIPPED_DATE_KEY, plateId, null)) {
        final String shipDateValue = plateId.getString(SHIPPED_DATE_KEY);
        try {
            final SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_US_DASHES);
            sdf.setLenient(false);
            sdf.parse(shipDateValue);
        } catch (ParseException e) {
            retValue = false;
            errorMessages.add("Element " + SHIPPED_DATE_KEY + " must be in "
                    + DATE_FORMAT_US_DASHES.toUpperCase() + " format , instead " + shipDateValue + " found.");
        }
    } else {
        retValue = false;
    }
    return retValue;
}

From source file:org.finra.herd.service.helper.BusinessObjectDataHelper.java

/**
 * Gets a date in a date format from a string format or null if one wasn't specified. The format of the date should match
 * HerdDao.DEFAULT_SINGLE_DAY_DATE_MASK.
 *
 * @param dateString the date as a string
 *
 * @return the date as a date or null if one wasn't specified or the conversion fails
 *//*from ww  w .j  a  v a2s  .co  m*/
public Date getDateFromString(String dateString) {
    Date resultDate = null;

    // For strict date parsing, process the date string only if it has the required length.
    if (dateString.length() == AbstractHerdDao.DEFAULT_SINGLE_DAY_DATE_MASK.length()) {
        // Try to convert the date string to a Date.
        try {
            // Use strict parsing to ensure our date is more definitive.
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
                    AbstractHerdDao.DEFAULT_SINGLE_DAY_DATE_MASK, Locale.US);
            simpleDateFormat.setLenient(false);
            resultDate = simpleDateFormat.parse(dateString);
        } catch (ParseException e) {
            // This assignment is here to pass PMD checks.
            resultDate = null;
        }
    }

    return resultDate;
}

From source file:org.kuali.kfs.module.cam.batch.service.impl.AssetBarcodeInventoryLoadServiceImpl.java

/**
 * @see org.kuali.module.cams.service.AssetBarCodeInventoryLoadService#processFile(java.io.File)
 *//*from  w  w w  .ja va  2s  .c om*/
public boolean processFile(File file, AssetBarCodeInventoryInputFileForm form) {
    LOG.debug("processFile(File file) - start");

    // Removing *.done files that are created automatically by the framework.
    this.removeDoneFile(file);

    BufferedReader input = null;
    String fileName = file.getName();

    String day;
    String month;
    String year;
    String hours;
    String minutes;
    String seconds;
    boolean isValid = true;

    SimpleDateFormat formatter = new SimpleDateFormat(
            CamsConstants.DateFormats.MONTH_DAY_YEAR + " " + CamsConstants.DateFormats.MILITARY_TIME,
            Locale.US);
    formatter.setLenient(false);

    BarcodeInventoryErrorDetail barcodeInventoryErrorDetail;
    List<BarcodeInventoryErrorDetail> barcodeInventoryErrorDetails = new ArrayList<BarcodeInventoryErrorDetail>();

    List<BarcodeInventoryErrorDocument> barcodeInventoryErrorDocuments = new ArrayList<BarcodeInventoryErrorDocument>();
    try {
        Long ln = new Long(1);
        input = new BufferedReader(new FileReader(file));
        String line = null;

        while ((line = input.readLine()) != null) {
            line = StringUtils.remove(line, "\"");
            String[] lineStrings = org.springframework.util.StringUtils.delimitedListToStringArray(line, ",");

            // Parsing date so it can be validated.
            lineStrings[2] = StringUtils.rightPad(lineStrings[2].trim(), 14, "0");

            day = lineStrings[2].substring(0, 2);
            month = lineStrings[2].substring(2, 4);
            year = lineStrings[2].substring(4, 8);
            hours = lineStrings[2].substring(8, 10);
            minutes = lineStrings[2].substring(10, 12);
            seconds = lineStrings[2].substring(12);

            String stringDate = month + "/" + day + "/" + year + " " + hours + ":" + minutes + ":" + seconds;
            Timestamp timestamp = null;

            // If date has invalid format set its value to null
            try {
                timestamp = new Timestamp(formatter.parse(stringDate).getTime());
            } catch (Exception e) {
            }

            // Its set to null because for some reason java parses "00000000000000" as 0002-11-30
            if (lineStrings[2].equals(StringUtils.repeat("0", 14))) {
                timestamp = null;
            }

            barcodeInventoryErrorDetail = new BarcodeInventoryErrorDetail();
            barcodeInventoryErrorDetail.setUploadRowNumber(ln);
            barcodeInventoryErrorDetail.setAssetTagNumber(lineStrings[0].trim());
            barcodeInventoryErrorDetail.setUploadScanIndicator(
                    lineStrings[1].equals(CamsConstants.BarCodeInventory.BCI_SCANED_INTO_DEVICE));
            barcodeInventoryErrorDetail.setUploadScanTimestamp(timestamp);
            barcodeInventoryErrorDetail.setCampusCode(lineStrings[3].trim().toUpperCase());
            barcodeInventoryErrorDetail.setBuildingCode(lineStrings[4].trim().toUpperCase());
            barcodeInventoryErrorDetail.setBuildingRoomNumber(lineStrings[5].trim().toUpperCase());
            barcodeInventoryErrorDetail.setBuildingSubRoomNumber(lineStrings[6].trim().toUpperCase());
            barcodeInventoryErrorDetail.setAssetConditionCode(lineStrings[7].trim().toUpperCase());
            barcodeInventoryErrorDetail
                    .setErrorCorrectionStatusCode(CamsConstants.BarCodeInventoryError.STATUS_CODE_ERROR);
            barcodeInventoryErrorDetail.setCorrectorUniversalIdentifier(
                    GlobalVariables.getUserSession().getPerson().getPrincipalId());

            barcodeInventoryErrorDetails.add(barcodeInventoryErrorDetail);
            ln++;
        }
        processBarcodeInventory(barcodeInventoryErrorDetails, form);

        return true;
    } catch (FileNotFoundException e1) {
        LOG.error("file to parse not found " + fileName, e1);
        throw new RuntimeException(
                "Cannot find the file requested to be parsed " + fileName + " " + e1.getMessage(), e1);
    } catch (Exception ex) {
        LOG.error("Error reading file", ex);
        throw new IllegalArgumentException("Error reading file: " + ex.getMessage(), ex);
    } finally {
        LOG.debug("processFile(File file) - End");

        try {
            if (input != null) {
                input.close();
            }
        } catch (IOException ex) {
            LOG.error("loadFlatFile() error closing file.", ex);
        }
    }
}

From source file:org.dspace.discovery.SolrServiceImpl.java

/**
 * Helper function to retrieve a date using a best guess of the potential
 * date encodings on a field/*  w ww  .  j  a  v  a 2 s  .c  o  m*/
 *
 * @param t the string to be transformed to a date
 * @return a date if the formatting was successful, null if not able to transform to a date
 */
public static Date toDate(String t) {
    SimpleDateFormat[] dfArr;

    // Choose the likely date formats based on string length
    switch (t.length()) {
    case 4:
        dfArr = new SimpleDateFormat[] { new SimpleDateFormat("yyyy") };
        break;
    case 6:
        dfArr = new SimpleDateFormat[] { new SimpleDateFormat("yyyyMM") };
        break;
    case 7:
        dfArr = new SimpleDateFormat[] { new SimpleDateFormat("yyyy-MM") };
        break;
    case 8:
        dfArr = new SimpleDateFormat[] { new SimpleDateFormat("yyyyMMdd"), new SimpleDateFormat("yyyy MMM") };
        break;
    case 10:
        dfArr = new SimpleDateFormat[] { new SimpleDateFormat("yyyy-MM-dd") };
        break;
    case 11:
        dfArr = new SimpleDateFormat[] { new SimpleDateFormat("yyyy MMM dd") };
        break;
    case 20:
        dfArr = new SimpleDateFormat[] { new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'") };
        break;
    default:
        dfArr = new SimpleDateFormat[] { new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") };
        break;
    }

    for (SimpleDateFormat df : dfArr) {
        try {
            // Parse the date
            df.setCalendar(Calendar.getInstance(TimeZone.getTimeZone("UTC")));
            df.setLenient(false);
            return df.parse(t);
        } catch (ParseException pe) {
            log.error("Unable to parse date format", pe);
        }
    }

    return null;
}